简体   繁体   中英

Python OOP Inheritance: Method Resolution Order (MRO)

There is an variation in the output when i used Method Resolution Order (MRO). Can anyone explain why this difference in the result.

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'>)

Your output is just inverse because you traverse the inheritance tree in post-order . You first traverse the hierarchy and then print out the statement. You need to switch this behaviour. Print (visit the node) first and then traverse the hierarchy.

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

You have to print the statement first and then traverse the hierarchy:

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

Change the order of your print:

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

First call to super in D will get the code to B's super. In B's super call the mro of D will be used and mro will be (C, A, object). This will land to C's super. here again D's mro will be used which will be (A, object). Therefore the ouput will ACBD

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM