Python - 多重继承:是否存在在所有祖先上执行该方法的关键字?

时间:2012-09-05 02:27:00

标签: python inheritance multiple-inheritance

考虑:

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

2 个答案:

答案 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