Search⌘ K

Method Resolution Order (MRO)

Explore the concept of Python's Method Resolution Order (MRO) and how it determines the order in which base classes are searched when using inheritance. Understand the enhancements in Python 3's super function and how it simplifies calling methods in parent classes. This lesson helps you navigate complex class hierarchies and write forward-compatible Python code using super and MRO.

Overview of MRO

Method Resolution Order (MRO) is just a list of types that the class is derived from. ​​So if we have a class that inherits from two other classes, we might think that its MRO will be itself and the two parents it inherits from. However the parents also inherit from Python’s base class: Object.

Simple example of MRO

Let’s take a look at an example that will make this clearer:

Python 3.5
class X:
def __init__(self):
print('X')
super().__init__()
class Y:
def __init__(self):
print('Y')
super().__init__()
class Z(X, Y):
pass
z = Z()
print(Z.__mro__)

Here we create three classes. The first two just print out the name of the class and the last one inherits from the previous two.

As we can see, when we instantiate the classes, each of the parent classes prints out its name. Then we get the Method Resolution Order, which is ZXY and object.

Overriding a base class

Another good example to look at is to see what happens when we create a class variable in the base class and then override it later:

Python 3.5
class Base:
var = 5
def __init__(self):
pass
class X(Base):
def __init__(self):
print('X')
super().__init__()
class Y(Base):
var = 10
def __init__(self):
print('Y')
super().__init__()
class Z(X, Y):
pass
z = Z()
print(Z.__mro__)
print(super(Z, z).var)

...