Sobes.tech
Middle

What is MRO and how does it work?

sobes.tech AI

Answer from AI

MRO (Method Resolution Order) is the order in which Python searches for methods and attributes in a class hierarchy during inheritance, especially in the case of multiple inheritance.

Python uses the C3 linearization algorithm to compute the MRO. It guarantees that:

  • Each class appears in the MRO after its parents.
  • The method search order is unambiguous and predictable.

For example, if class C inherits from A and B, the MRO determines the order in which Python will search for methods: first in C, then in A, then in B, or vice versa, depending on the hierarchy.

Example:

class A:
    def method(self):
        print("A")

class B(A):
    def method(self):
        print("B")

class C(A):
    def method(self):
        print("C")

class D(B, C):
    pass

print(D.mro())  # Shows the method search order
D().method()    # Will print "B" because B comes before C in the MRO

Thus, MRO helps avoid ambiguities when calling methods in complex inheritance hierarchies.