Python super() 链没有前进

Python super() chain not advancing

Python 这里是新手,希望对多重继承有帮助!

考虑以下 class 层次结构:

class Base1:
    def display(self):
        print('Base1')

class Base2:
    def display(self):
        print('Base2')

class Derived1 (Base1):
    def display(self):
        super().display()
        print('Derived1')

class Derived2 (Base2):
    def display(self):
        super().display()
        print('Derived2')

class Derived (Derived1, Derived2):
    def display(self):
        super().display()
        print('Derived')

Derived().display()

我原以为它的输出会打印层次结构中涉及的所有 classes 的名称,但事实并非如此。此外,如果我将 super().display() 添加到 Base1Base2,我会得到错误 AttributeError: 'super' object has no attribute 'display'.

怎么了?

Base1Base2 隐式继承自没有 display 方法的 object。这解释了 AttributeError: 'super' object has no attribute 'display' 异常。

这段代码的输出应该是:

Base1
Derived1
Derived

从多个 类 继承时,在调用 super 时从左到右搜索它们的属性。因此,display 是在 Derived1 上找到的,因此在方法解析期间不会查看 Derived2。有关详细信息,请参阅 this question