user1845156
user1845156

Reputation: 31

python: how to inherit from a dynamically inherited class?

i'm writing a python(python 2.7) program. I want to create a class that inherits from a class that dynamically inherits from another class. can such a thing be done?

for example:

class A(Object):
    def print_me():
        print "A"

class B(Object):
    def print_me():
        print "B"

class son(<inherits from A or B dynamically, depending on the input>):
    pass

class grand_son(son):
    pass

what i want is that in the following code:

 grand_son("A").print_me()

will print:

 >> A

and the following code:

 grand_son("B").print_me()

will print:

 >> B

can it be done?

Thanks.

Upvotes: 1

Views: 117

Answers (1)

jq170727
jq170727

Reputation: 14725

You can use the three argument form of type() to dynamically create a class.

Here is an interactive demonstration:

>>> class A(object):
...   def print_me(self):
...     print "A"
... 
>>> class B(object):
...   def print_me(self):
...     print "B"
... 
>>> def getclass(name):
...   return {"A":A, "B":B}[name]
... 
>>> def getson(parent):
...   return type("son", (getclass(parent),), {})
... 
>>> son = getson("A")
>>> son().print_me()
A
>>> son = getson("B")
>>> son().print_me()
B

With this you can define a grand_son function as so:

>>> def grand_son(grandparent):
...   return type("grand_son", (getson(grandparent),), {})
... 
>>> grand_son("A")().print_me()
A
>>> grand_son("B")().print_me()
B
>>> 

Upvotes: 2

Related Questions