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

2024-04-19 23:34:45 发布

您现在位置:Python中文网/ 问答频道 /正文

考虑:

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

这引出了我的问题。有没有什么uber秘密方法可以让Python在所有祖先上调用这个方法,而不需要我像代码一样显式地这样做,比如(我在这里编了all\u祖先关键字-这样的东西真的存在吗?)地址:

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

Tags: to方法selfherefoodefplussome
2条回答

不,没有秘密的方法。正如我在您的另一个问题中提到的,通常的方法是不从单个后代类调用所有祖先方法。相反,每个类应该使用super来调用一个祖先方法,即继承链上的下一个。如果树中的每个类都这样做(除了最顶层的基类),那么所有方法都将按顺序被调用。换句话说,Foo应该使用super(),它将调用X的方法;然后X也应该使用super(),它将调用Y的方法。你知道吗

为了使这项工作正常,通常最好在继承树中有一个最顶层的类。在您的示例中,这将是一个以X和Y为基的类。您需要这样一个类作为super调用序列的最后一站;这个基类应该而不是调用super。如果您一直到处调用super,最终它将尝试调用基类object,然后失败,因为object没有提供您尝试调用的方法。你知道吗

如果您可以为X&;Y提供一个公共基类或mix-in,这应该可以:

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中声明基类的顺序调用。你知道吗

相关问题 更多 >