Method Resolution Order (MRO) in Python Made Easy

Nkugwa Mark William
2 min readFeb 6, 2023

--

Method Resolution Order (MRO) can be thought of as a “search path” that Python follows to determine which method should be executed in a class hierarchy. When a method is called in a derived class, Python searches the method definition in the derived class first. If the method is not found there, Python moves up the hierarchy to the parent class, and continues the search until it finds the method definition or reaches the root class. This search order is determined by the MRO, which defines the order in which Python searches for a method in the inheritance hierarchy.

A simple analogy for MRO can be thought of as a library. When a person is looking for a book, they start by searching in the section where the book should be placed. If it’s not there, they move to the next section, and so on, until they find the book or run out of sections to search in. In the same way, Python uses the MRO to find the correct method definition for a method call in an inheritance hierarchy.

In Python, MRO is determined using C3 Linearization algorithm which provides a deterministic and efficient resolution order by combining multiple inheritance trees into a single method resolution order.

For example, consider the following class hierarchy:

class A:
def m(self):
print("method from A")

class B(A):
def m(self):
print("method from B")

class C(A):
def m(self):
print("method from C")

class D(B, C):
pass

Here, class D has two parent classes B and C which both inherit from class A. If a method m is called on an instance of class D, the MRO of class D determines the order in which the parent classes are searched for the method m. In this case, the MRO of class D is [D, B, C, A], so the method from class B is called.

d = D()
d.m() # Output: method from B

It’s important to understand the MRO concept when working with multiple inheritance in Python as it affects the behavior of method resolution in cases where the same method name is present in multiple parent classes.

--

--

Nkugwa Mark William
Nkugwa Mark William

Written by Nkugwa Mark William

Nkugwa Mark William is a Chemical and Process engineer , entrepreneur, software engineer and a technologists with Apps on google play store and e commerce sites

No responses yet