Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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(unspecifiedParentClass):
    # something

instance = Child(SomeParentClass)

This obviously does not work. But is it possible to do this somehow?

like image 904
Thrasi Avatar asked Sep 08 '13 11:09

Thrasi


2 Answers

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

class Child(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...

class SomeParentClass(object):
    def __init__(self):
        print 'initializing SomeParentClass instance'
    def hello(self):
        print 'in SomeParentClass.hello()'

c = Child(SomeParentClass)
c.hello()

Output:

initializing SomeParentClass instance
initializing Child instance
in SomeParentClass.hello()
like image 154
martineau Avatar answered Oct 07 '22 06:10

martineau


Have you tried something like this?

class SomeParentClass(object):
    # ...
    pass

def Child(parent):
    class Child(parent):
        # ...
        pass

    return 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.

like image 24
Lethargy Avatar answered Oct 07 '22 08:10

Lethargy