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
Xprecedes classYin all linearization of the parents of a class, then it will also precedes classYin the final linearization.
class A:
pass
class B(A):
pass
class D(B, A):
pass
d = D()
d.__mro__ # D, B, AExample from Python Cookbook
Mixins
A mixin is a special kind of multiple inheritance. There are two main situations where mixins are used:
- You want to provide a lot of optional features for a class.
- You want to use one particular feature in a lot of different classes.
References
- https://github.com/matacoder/senior#multiple-inheritance
- https://www.youtube.com/watch?v=IqwWxZrMcx4
- https://medium.com/technology-nineleaps/python-method-resolution-order-4fd41d2fcc
- https://medium.com/@__hungrywolf/mro-in-python-3-e2bcd2bd6851
- https://www.geeksforgeeks.org/method-resolution-order-in-python-inheritance/