Method Resolution Order (MRO)

Let's discuss MRO and how it can be useful.

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:

Press + to interact
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:

Press + to interact
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)

...