Sobes.tech
Junior — Middle

Как осуществляется последовательность вызова методов в случае множественного наследования в Python?

sobes.tech AI

Answer from AI

In Python, the method call order in multiple inheritance is determined by the Method Resolution Order (MRO) algorithm. MRO is a linear order in which Python searches for methods and attributes in classes when called.

MRO is constructed using the C3 linearization algorithm, which guarantees that:

  • A class always precedes its parents.
  • The inheritance order is preserved.
  • There are no conflicts in resolving the order.

To view a class's MRO, you can use the __mro__ attribute or the mro() function:

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__)
# (<class '__main__.D'>, <class '__main__.B'>, <class '__main__.C'>, <class '__main__.A'>, <class 'object'>)

obj = D()
obj.method()  # Calls the method from B, as B comes before C in the MRO

Thus, when calling a method, Python searches for it in classes according to the MRO, starting from the most derived class.