【发布时间】:2010-12-31 16:25:09
【问题描述】:
我在 python 中有一个“D”类的对象,我想依次执行“D”定义的“运行”方法及其每个祖先(“A”、“B”和“C”) .
我可以这样做
class A(object):
def run_all(self):
# I prefer to execute in revere MRO order
for cls in reversed(self.__class__.__mro__):
if hasattr(cls, 'run'):
# This works
cls.run(self)
# This doesn't
#cls.__getattribute__(self, 'run')()
def run(self):
print "Running A"
class B(A):
def run(self):
print "Running B"
class C(A):
def run(self):
print "Running C"
class D(C, B):
def run(self):
print "Running D"
if __name__ == "__main__":
D().run_all()
结果
$ python test.py
Running A
Running B
Running C
Running D
但实际上我不知道要执行的方法的名称。但是,如果我使用 getattribute() (请参阅注释)行尝试此操作,它将不起作用:
$ python test.py
Running D
Running D
Running D
Running D
所以我的问题是:
为什么不起作用?
这是最好的解决方法吗?
【问题讨论】: