考虑:
class X:
def some_method(self):
print("X.some_method called")
class Y:
def some_method(self):
print("Y.some_method called")
class Foo(X,Y):
def some_method(self):
super().some_method()
# plus some Foo-specific work to be done here
foo_instance = Foo()
foo_instance.some_method()
输出:
X.some_method called
将Foo的类声明切换为:
class Foo(Y,X):
将输出更改为:
Y.some_method called
如果我想要调用两个祖先方法,我可以将Foo的实现改为:
def some_method(self):
X().some_method()
Y().some_method()
# plus some Foo-specific work to be done here
这引出了我的问题。是否有任何秘密的方法可以让Python在所有祖先上调用该方法而不像代码那样明确地执行此操作,例如(我在这里编写了all_ancestors关键字 - 这样的事情确实存在吗?):
def some_method(self):
all_ancestors().some_method()
# plus some Foo-specific work to be done here
预期输出为:
X.some_method called
Y.some_method called
答案 0 :(得分:2)
不,没有秘密的方法可以做到这一点。正如我在你的另一个问题中所提到的,通常的做法是不要从单个后代类调用所有祖先方法。相反,每个类应该使用super
来调用一个祖先方法,即继承链中的下一个方法。如果树中的每个类都执行此操作(除了最顶层的基类),那么将按顺序调用所有方法。换句话说,Foo应该使用super()
,这将调用X
的方法;然后X
也应使用super()
,这将调用Y
的方法。
为了使这项工作正常,通常最好在继承树中拥有一个最顶层的类。在你的例子中,这将是一个类,它是X和Y的基础。你需要这样一个类作为super
调用序列的最后一个句点;这个基类应该不调用super。如果你只是一直在调用super
,最终它会尝试调用基类object
类,然后失败,因为object
没有提供你试图调用的方法
答案 1 :(得分:0)
如果您能提供X
& Y
具有公共基类或混合,这应该有效:
class ISomeMethod:
def some_method(self):
pass
class X(ISomeMethod):
def some_method(self):
print("X.some_method called")
super(X, self).some_method()
class Y(ISomeMethod):
def some_method(self):
print("Y.some_method called")
super(Y, self).some_method()
然后应按照some_method
中声明基类的顺序调用 Foo
。