I am relatively new to python OOP. Although I have some experience with JAVA OOP and I know the meaning of the method 'super', I struggle to understand how does it works in python when I have multiple inheritances (which doesn't exist in JAVA)
After digging to find some answers, I read that according to the inheritances graph, for every class python made a Method Resolution Order (MRO) to determine in what order to look for an instance method.
I also read that the MRO is determined by "old style" or "new style", depending on my python version. I have python 3.7 so I use the "new style" method.
If I understand correctly, every time I override a method and call 'super', python goes to the method in the class that appears after the current class in the MRO.
Indeed, When I run the following code:
class A(object):
def go(self):
print("go A go!")
class B(A):
def go(self):
super(B, self).go()
print("go B go!")
class C(A):
def go(self):
super(C, self).go()
print("go C go!")
class D(B,C):
def go(self):
super(D, self).go()
print("go D go!")
if __name__ == "__main__":
d = D()
d.go()
print(D.__mro__)
I got the output:
go A go!
go C go!
go B go!
go D go!
(<class '__main__.D'>, <class '__main__.B'>, <class '__main__.C'>, <class '__main__.A'>, <class 'object'>)
So far so good, but when I tried to run the following code:
class A(object):
def foo(self):
print('this is A')
class B(object):
def foo(self):
print('this is B')
class AB(A,B):
def foo(self):
super(AB,self).foo()
print('this is AB')
if __name__ == '__main__':
x = AB()
x.foo()
print(AB.__mro__)
I got the output:
this is A
this is AB
(<class '__main__.AB'>, <class '__main__.A'>, <class '__main__.B'>, <class 'object'>)
Rather than the output as I was expected to be:
this is B
this is A
this is AB
(<class '__main__.AB'>, <class '__main__.A'>, <class '__main__.B'>, <class 'object'>)
So apparently I don't understand what is going on...
Any explanation for this situation, and also about how exactly python determines the MRO (according to the "new style") will be greatly appreciated!