What is the MRO in Python?

Last updated 3 weeks, 4 days ago | 20 views 75     5

Tags:- Python

MRO stands for Method Resolution Order. Talking of multiple inheritances, whenever we search for an attribute in a class, Python first searches in the current class. If found, its search is satiated. If not, it moves to the parent class. It follows an approach that is left-to-right and depth-first.

 
class A:
    def m(self):
        print("In A")
       
class B(A):
    def m(self):
        print("In B")
 
class C(A):
    def m(self):
        print("In C") 
        
class D(B, C):
    pass  

     
obj = D()
obj.m()

Note: When you call obj.m() (m on the instance of Class D) the output is [In B]. If Class D is declared as D(C, B) then the output of obj.m() will be [In C].
This happens because of MRO(Method Resolution Order)

So we could say that:

class A: 
    pass

class B(A): 
    pass 

class C(A): 
    pass

class D(C,B): 
    pass

is a way of specifying the inheritance chain:

D → C → B → A


We can call this order a linearization of the class Child; the set of rules applied is the Method Resolution Order (MRO). We can borrow the __mro__ attribute or the mro() method to get this.