MRO in multiple inheritance
MRO (method resolution order) determines which call happens in case of multiple inheritance. There can be a diamond multiple inheritance where two base classes of a subclass has same base class. For example,
G
/ \
A B
\ /
C
In code,
class G:
def call(self):
print("Call from G")
class A(G):
def call(self):
super().call()
print("Called from A")
class B(G):
def call(self):
print("Called from B")
class C(A, B):
passIf we call call on instance of class C as shown below,
c = C()
c.call()how the order of print comes? which class method super().call() in class A refer to? Will it refer to A’s parent class G’s call()? Answer to this question is given by mro of class C. If we do,
C.mro()It prints
[<class '__main__.C'>, <class '__main__.A'>, <class '__main__.B'>, <class '__main__.G'>, <class 'object'>]
This remains same through out for the call made on c.call(), which means, super().call() in a A follows MRO for C where B’s call is there.
So, this should help us to determine the order of print calls, which should be,
Called from B
Called from A
References
- https://fuhm.net/super-harmful/ (Good to have a read)