Skip to content Skip to sidebar Skip to footer

Selective Inheritance Python

I am making a python program which is using classes, I want one class to only selectively inherit from another e.g: class X(object): def __init__(self): self.hello = 'h

Solution 1:

In Python classes can be created at run-time:

classX(object):
    def__init__(self):
        self.hello = 'hello'classY(object):
    def__init__(self):
        self.moo = 'moo'defcreate_class_Z(mode):
    base_class = globals()[mode]
    classZ(base_class):
        def__init__(self):
            base_class.__init__(self)
    return Z

ZX = create_class_Z('X')
zx = ZX()
print(zx.hello)

ZY = create_class_Z('Y')
zy = ZY()
print(zy.moo)

Solution 2:

You can do this by overriding __new__ and changing the cls passed in (you're creating a new type by appending X or Y as a base class):

classX(object):def__init__(self):
        self.hello = 'hello'classY(object):def__init__(self):
        self.moo = 'moo'classZ(object):def__new__(cls, mode):
        mixin = {'X': X, 'Y': Y}[mode]
        cls = type(cls.__name__ + '+' + mixin.__name__, (cls, mixin), {})
        returnsuper(Z, cls).__new__(cls)
    def__init__(self, mode, *args, **kwargs):
        super(Z, self).__init__(*args, **kwargs)

Note that you need to bypass Z.__new__ using super to avoid infinite recursion; this is the standard pattern for __new__ special override methods.

Solution 3:

I think you'd better define two members within Z,one is a class instance of X,another is a instance of Y.You can get the associated information stored in these instances while use different mode.

Solution 4:

A solution using type:

class_Z(): pass#rename your class Z to thisdefZ(mode): #this function acts as the constructor for class Z
    classes = {'X': X, 'Y': Y, 'Foo': Bar} #map the mode argument to the base cls#create a new type with base classes Z and the class determined by mode
    cls = type('Z', (_Z, classes[mode]), {})
    #instantiate the class and return the instancereturn cls()

Post a Comment for "Selective Inheritance Python"