Sobes.tech
Junior — Middle

How does attribute resolution occur in case of multiple inheritance in object-oriented programming?

sobes.tech AI

Answer from AI

In Python, attribute resolution in multiple inheritance occurs using the MRO (Method Resolution Order) algorithm — the order in which methods and attributes are searched in the class hierarchy.

MRO determines the order in which Python searches for attributes and methods when accessed through an object.

The C3 linearization algorithm is used to compute the MRO, which guarantees:

  • A linear order of class traversal
  • Preservation of the inheritance order
  • No conflicts or cycles

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

obj = D()
obj.method()  # Will print "B"
print(D.mro())

Here, D.mro() returns the order: [D, B, C, A, object]. When calling obj.method(), Python searches for the method in D, then in B (found), and stops.

Thus, attribute resolution in Python's multiple inheritance follows the MRO, computed by the C3 linearization algorithm.

How does attribute resolution occur in case of… - sobes.tech