Understanding Method Resolution Order (MRO) in Python: An Overview

Sharing

Click to Home

Log Issues

Click to Log Issue

Description:

MRO stands for Method Resolution Order. It refers to the order in which the base classes of a class hierarchy are searched when looking for a method with a particular name. In Python, the MRO is determined by the C3 algorithm, which provides a consistent order for method resolution across all classes in a hierarchy, regardless of their interrelationships.

Here is an example of a simple class hierarchy with three classes: A, B, and C, where C inherits from both A and B. In this example, A and B have a method with the same name, foo(), and C inherits from both:
 

class A:
    def foo(self):
        print("This is A's foo()")

class B:
    def foo(self):
        print("This is B's foo()")

class C(A, B):
    pass

c = C()
c.foo()

When the foo() method is called on an instance of C, the MRO is used to determine which version of the method should be called.

In this case, the MRO used by Python is C3 which is linearization of the hierarchy, it will look for the method in the following order:

  1. C
  2. A
  3. B

The first class that contains the method will be the one that is used. So the output of the above code will be:

This is A's foo()

It means the first implementation of foo() method is in class A, so it will be called. If foo() method is not present in class A, python will look into class B.


Click to Home