Sobes.tech
Junior — Middle

How does method or attribute lookup work in the inheritance chain in Python?

sobes.tech AI

Answer from AI

In Python, the search for a method or attribute in the inheritance chain is performed using the MRO (Method Resolution Order) algorithm. When accessing an attribute, the interpreter first looks in the object itself, then in its class, and then in the base classes in the order determined by the MRO.

For classes with multiple inheritance, the C3 linearization algorithm is used, which creates a search sequence considering the inheritance order and avoiding conflicts.

Example:

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

class B(A):
    pass

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

class D(B, C):
    pass

obj = D()
obj.method()  # Will print "C"

Here, the method is searched in D, then B, then C, then A. Since B does not override the method, the search continues and finds the method in C.