Skip to main content
 首页 » 编程设计

python之理解菱形继承(钻石问题)中的super()

2025年05月04日10TianFang

我正在学习python,开始学习继承中的MRO。

我已经阅读了 super 的用法及其使用方式,但是我无法理解以下问题。如果它不是 super 我知道 B 被称为。 D->B->C->A 但是当添加了 super 时,我不知道为什么输出是这样的

class A: 
    def test(self): 
        print("test of A called") 
class B(A): 
    def test(self): 
        print("test of B called") 
        super().test() 
class C(A): 
    def test(self): 
        print("test of C called") 
        super().test() 
class D(B, C): 
    def test2(self): 
        print("test of D called") 
obj=D() 
obj.test() 

输出

test of B called 
test of C called 
test of A called 

请帮助我了解 super 在这里是如何运作的。

请您参考如下方法:

super() 将按照 Python 遵循 C3 线性化 ( https://en.wikipedia.org/wiki/C3_linearization ) 的方法解析顺序转到下一个类:子级在其父级之前被调用,并且多个父级按顺序被调用它们被设置在其中。

因此,如果您调用类 D 中的方法,则 MRO 是 D -> B -> C -> A,但是例如如果您最初在类 B 中调用它,则 MRO 是 B -> A。

这样是不是更清楚了?

编辑:所以在你的例子中: 您调用不存在的 D.test(),因此它被委托(delegate)给打印字符串然后调用 super()< 的 B.test()/。由于如上所述的 MRO,B 的 super() 在这种情况下是 C,因此接下来调用 C.test(),然后最终调用 A .test().