Python: Method Resolution Order(MRO) in Inheritance
Lets consider the following python code:
class A: def do(self): print("From the class: A")
What would be the output of following?
inst= F()
class A: def do(self): print("From the class: A")
class B(A):
def do(self):
print("From the class: B")
class C(A): def do(self): print("From the class: C")
class D(C): pass
class E(D, B): pass class F(E): pass
class C(A): def do(self): print("From the class: C")
class D(C): pass
class E(D, B): pass class F(E): pass
What would be the output of following?
inst= F()
inst.do()
Well, to understand this we should know the method resolution order in python's inherited
classes. In Python 2.x, the resolution algorithm is: Search Deep first & then Left to Right
order. That is In above example, the Order would be F->E->D->C->A->B-A
So the output will be : From the class: C
However, In Python 3.x, the resolution algorithm is: Left to Right first & Deep.
That is in above example the resolution order will be : F->E->D->B->C->A
So the output will be : From the class: B
For Details, refer to : https://en.wikipedia.org/wiki/C3_linearization
Well, to understand this we should know the method resolution order in python's inherited
classes. In Python 2.x, the resolution algorithm is: Search Deep first & then Left to Right
order. That is In above example, the Order would be F->E->D->C->A->B-A
So the output will be : From the class: C
However, In Python 3.x, the resolution algorithm is: Left to Right first & Deep.
That is in above example the resolution order will be : F->E->D->B->C->A
So the output will be : From the class: B
For Details, refer to : https://en.wikipedia.org/wiki/C3_linearization
Comments