'Multilevel and Multiple inheritance using super() in Python returns odd result
if I type this this code,
class A:
pass
class B(A):
def show_letter(self):
print("This is B")
class C(B):
def show_letter(self):
super().show_letter()
print("This is C")
class E(B):
def show_letter(self):
super().show_letter()
print("This is E")
class D(C, E):
division = "North"
def show_letter(self):
super().show_letter()
print("This is D")
div1 = D()
div1.show_letter()
it returns:
This is B
This is E
This is C
This is D
Why is there "E" printed ? If I delete super() in C class, "E" is not printed. Thank you.
Solution 1:[1]
This is because the method resolution order. The first call is in D, then it calls C due to the arguments order: D(C, E). It could call B as parent but the latter is also a parent for E, so it is called the first. Only after that there is a B call. Thereby your call order is D -> C -> E -> B & the print order is revered.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Vovin |
