Python 多重继承超级方法调用

Python Multiple Inheritance super method call

我正在阅读 this 文章,但我无法理解以下示例:

class Class1: 
    def m(self): 
      print("In Class1") 
      print("here1")
  
class Class2(Class1): 
    def m(self): 
        print("In Class2") 
        super().m() 
        print("here2")
  
class Class3(Class1): 
    def m(self): 
        print("In Class3") 
        super().m() 
        print("here3")
  
class Class4(Class2, Class3): 
    def m(self): 
        print("In Class4")    
        super().m() 
       
obj = Class4() 
obj.m() 

结果是:

In Class4
In Class2
In Class3
In Class1
here1
here3
here2

为什么打印结果是这样的?我预计结果是:

In Class4
In Class2
In Class1
here1
here2
In Class3
In Class1
here1
here3

为什么输入Class2super().m()被丢弃了?它仅在我们完成打印“In Class3”时运行。

谢谢

它首先打印所有 class 位置的顺序,因为您正在调用超级 class

def m(self): 
    print("In Class3") 
    super().m() 
    print("here3")

看到你正在调用 super().m() 这将导致父 classes self 函数变为 运行 在该函数中包含 print("In Classn") 语句,然后将调用下一个 super().m() 导致另一个自函数为 运行。您需要先打印这里。

那是因为 Python 的方法解析顺序。 例如,您可以通过调用 Class4.mro() 查看 类 的 MRO。 您会看到 Class3 出现在 Class1 之前。这是因为 Python 的 MRO (https://www.python.org/download/releases/2.3/mro/) uses the C3 Linearization algorithm (https://en.wikipedia.org/wiki/C3_linearization).

引用 Guido van Rossum(来自维基百科):

Basically, the idea behind C3 is that if you write down all of the ordering rules imposed by inheritance relationships in a complex class hierarchy, the algorithm will determine a monotonic ordering of the classes that satisfies all of them. If such an ordering can not be determined, the algorithm will fail.

您可以阅读该算法,但我喜欢对算法持这样一种简单的看法: 它基本上是一个从左到右的 DFS,但是子类总是比它的超类早。

注意:这是规则的简单视图,它不涵盖算法或失败案例,但在大多数情况下,这是记住 MRO 基础知识的好方法。