Skip to content Skip to sidebar Skip to footer

Pass A Parent Class As An Argument?

Is it possible to leave a parent class unspecified until an instance is created? e.g. something like this: class SomeParentClass: # something class Child(unspecifiedParentClas

Solution 1:

You can change the class of an instance in the class' __init__() method:

classChild(object):
    def__init__(self, baseclass):
        self.__class__ = type(self.__class__.__name__,
                              (baseclass, object),
                              dict(self.__class__.__dict__))
        super(self.__class__, self).__init__()
        print'initializing Child instance'# continue with Child class' initialization...classSomeParentClass(object):
    def__init__(self):
        print'initializing SomeParentClass instance'defhello(self):
        print'in SomeParentClass.hello()'

c = Child(SomeParentClass)
c.hello()

Output:

initializing SomeParentClass instance
initializing Child instance
in SomeParentClass.hello()

Solution 2:

Have you tried something like this?

classSomeParentClass(object):
    # ...passdefChild(parent):
    classChild(parent):
        # ...passreturn Child()

instance = Child(SomeParentClass)

In Python 2.x, also be sure to include object as the parent class's superclass, to use new-style classes.

Solution 3:

You can dynamically change base classes at runtime. Such as:

classSomeParentClass:
    # somethingclassChild():
    # somethingdefchange_base_clase(base_class):
    returntype('Child', (base_class, object), dict(Child.__dict__))()

instance = change_base_clase(SomeParentClass)

For example:

classBase_1:
    defhello(self):
        print('hello_1')

classBase_2:
    defhello(self):
        print('hello_2')

classChild:passdefadd_base(base):
    returntype('Child', (base, object), dict(Child.__dict__))()

# if you want change the Child class, just:defchange_base(base):
    global Child
    Child = type('Child', (base, object), dict(Child.__dict__))

defmain():
    c1 = add_base(Base_1)
    c2 = add_base(Base_2)
    c1.hello()
    c2.hello()

main()

Result:

hello_1
hello_2

Works well in both python 2 and 3.

For more information, see the related question How to dynamically change base class of instances at runtime?

Post a Comment for "Pass A Parent Class As An Argument?"