What is the MRO?
- Method resolution order defines the order in which the base classes are searched when executing a method.
- First, the method or attribute is searched within a class and then it follows the order we specified while inheriting.
- In multiple inheritances, the methods are executed based on the order specified while inheriting the classes.
Old style
Old style classes use DLR or depth-first left-to-right algorithm for MRO whereas new style classes use C3 Linearization algorithm for method resolution while doing multiple inheritances.
Diamond Problem
Python doesn't have this problem because of the method resolution order.
C3 linearization algorithm
C3 linearization algorithm enforces following constraints
- Child classes get checked before parents
- Multiple parents get checked in the order listed.
- If there are two valid choices for the next class, pick the one from the first parent.
C3 super-class linearization, it is based on 3 rules
- Inheritance graph determines the structure of method resolution order.
- Preserving local precedence ordering, i.e., visiting the super class only after the method of the local classes are visited.
- Monotonicity. If a class
X precedes class Y in all linearization of the parents of a class, then it will also precedes class Y in the final linearization.
class A:
pass
class B(A):
pass
class D(B, A):
pass
d = D()
d.__mro__ # D, B, A
Example from Python Cookbook