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

Copy

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

Copy

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

Copy


4. Diamond Problem in Multiple Inheritance

Copy


5. Using super() in MRO

Copy


6. Checking MRO with __mro__

Copy


7. Complex MRO with Multiple Inheritance

Copy


8. Reordering Base Classes

Copy


9. MRO with super() in Multiple Inheritance

Copy


10. Using inspect.getmro

Copy


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.

Last updated