Reputation: 83
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'>)
Upvotes: 4
Views: 966
Reputation: 1863
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
Upvotes: 3
Reputation: 677
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 A C B D
Upvotes: 2