当我使用方法解析顺序 (MRO) 时,输出会发生变化。谁能解释为什么结果存在这种差异。

class A:
    def __init__(self):
        pass
    def abc(self):
        print("A")
class B(A):
    def __init__(self):
        pass
    def abc(self):
        super().abc()
        print("B")
class C(A):
    def __init__(self):
        pass
    def abc(self):
        super().abc()
        print("C")
class D(B,C):
    def __init__(self):
        super().abc()
        print("D")
obj=D()
Output:
A
C
B
D

//Using Method Resolution Order (MRO):
    print(D.__mro__)
    Output:(<class '__main__.D'>, <class '__main__.B'>, <class '__main__.C'>, <class '__main__.A'>, <class 'object'>)

最佳答案

您的输出正好相反,因为您遍历 post-order 中的继承树。您首先遍历层次结构,然后打印出语句。你需要改变这种行为。先打印(访问节点),然后遍历层次结构。

 1. Loop:
 |
 +--1.1. Traversal (go hierarchy up)
 |
 +--1.2. Output (print)

您必须先打印语句,然后遍历层次结构:
 1. Loop:
 |
 +--1.1. Output (print)
 |
 +--1.2. Traversal (go hierarchy up)

更改打印顺序:
class A:
    def __init__(self):
        pass
    def abc(self):
        print("A")
class B(A):
    def __init__(self):
        pass
    def abc(self):
        print("B")
        super().abc()
class C(A):
    def __init__(self):
        pass
    def abc(self):
        print("C")
        super().abc()
class D(B,C):
    def __init__(self):
        print("D")
        super().abc()
obj=D()
Output:
D
B
C
A

关于Python OOP 继承 : Method Resolution Order (MRO),我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/32944357/

10-12 22:23