95. Method Resolution Order (MRO)

Here are 10 Python snippets to demonstrate Method Resolution Order (MRO) and how Python determines the order of method calls in multi-level and multiple inheritance scenarios:


1. Basic MRO in Single Inheritance

class A:
    def method(self):
        return "Method from A"

class B(A):
    pass

b = B()
print(b.method())  # Output: Method from A

2. Overriding a Method

class A:
    def method(self):
        return "Method from A"

class B(A):
    def method(self):
        return "Method from B"

b = B()
print(b.method())  # Output: Method from B

3. Multi-Level Inheritance


4. Diamond Problem in Multiple Inheritance


5. Using super() in MRO


6. Checking MRO with __mro__


7. Complex MRO with Multiple Inheritance


8. Reordering Base Classes


9. MRO with super() in Multiple Inheritance


10. Using inspect.getmro


Key Points About MRO:

  1. MRO stands for Method Resolution Order, the order in which Python looks for methods in a hierarchy of classes.

  2. Python uses the C3 Linearization Algorithm to determine the MRO in case of multiple inheritance.

  3. You can check the MRO of a class using:

    • ClassName.__mro__

    • inspect.getmro(ClassName)

    • help(ClassName)

  4. super() is resolved according to the MRO, making it easier to call parent class methods dynamically in a predictable order.

These examples illustrate how Python handles MRO, even in complex inheritance scenarios.

Last updated