method resolution order (MRO)
The method resolution order (MRO) is the order that Python follows to look up attributes and methods in a class hierarchy. It determines which method or attribute to use when names collide in multiple inheritance scenarios.
Python uses the C3 linearization algorithm to define this ordering.
Example
Say you have the following hyerarchy of classes and you need to know the MRO for class D
:
>>> class A:
... def speak(self):
... return "A"
...
>>> class B(A):
... pass
...
>>> class C(A):
... def speak(self):
... return "C"
...
>>> class D(B, C):
... pass
...
>>> D.__mro__
(
<class '__main__.D'>,
<class '__main__.B'>,
<class '__main__.C'>,
<class '__main__.A'>,
<class 'object'>
)
>>> D.mro()
[
<class '__main__.D'>,
<class '__main__.B'>,
<class '__main__.C'>,
<class '__main__.A'>,
<class 'object'>
]
You can view a class’s MRO using either the .__mro__
attribute or the .mro()
class method. You have to read the sequence from left to right—top to button in this example.
Python searches each class in that order until it finds the requested attribute or method. If the attribute or method doesn’t exist, then you get an AttributeError
exception.
Related Resources
Tutorial
Supercharge Your Classes With Python super()
In this step-by-step tutorial, you will learn how to leverage single and multiple inheritance in your object-oriented application to supercharge your classes with Python super().
For additional information on related topics, take a look at the following resources:
- Object-Oriented Programming (OOP) (Learning Path)
- Python Classes: The Power of Object-Oriented Programming (Tutorial)
- Inheritance and Composition: A Python OOP Guide (Tutorial)
- Supercharge Your Classes With Python super() (Course)
- Supercharge Your Classes With Python super() (Quiz)
- Class Concepts: Object-Oriented Programming in Python (Course)
- Inheritance and Internals: Object-Oriented Programming in Python (Course)
- Python Classes - The Power of Object-Oriented Programming (Quiz)
- Inheritance and Composition: A Python OOP Guide (Course)
- Inheritance and Composition: A Python OOP Guide (Quiz)