我正在写一个python(python2.7)程序。我想创建一个从一个动态继承另一个类的类继承的类。这样的事情能做吗?
例如:
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我想要的是在下面的代码中:
grand_son("A").print_me()将打印:
>> A和以下代码:
grand_son("B").print_me()将打印:
>> B这是可以做到的吗?
谢谢。
发布于 2017-09-28 23:53:24
您可以使用type()的三参数形式动态创建一个类。
下面是一个交互式演示:
>>> 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这样你就可以定义一个grand_son函数了:
>>> def grand_son(grandparent):
... return type("grand_son", (getson(grandparent),), {})
...
>>> grand_son("A")().print_me()
A
>>> grand_son("B")().print_me()
B
>>> https://stackoverflow.com/questions/46473182
复制相似问题