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.
We'll cover the following...
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:
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: