Junior — Middle
How is attribute searching carried out in case of multiple inheritance in object-oriented programming?
sobes.tech AI
Answer from AI
In Python, attribute lookup in multiple inheritance follows the MRO (Method Resolution Order) algorithm. MRO determines the order in which classes are traversed in the hierarchy to find the required attribute or method.
The MRO algorithm is built using the C3 linearization algorithm, which guarantees:
- A linear order of class traversal without conflicts.
- Preservation of the inheritance order.
When you access an attribute, Python searches for it in:
- The current class.
- The classes specified in the MRO, in order.
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
d = D()
d.method() # Will print "B" because B comes before C in D's MRO
print(D.mro())
Thus, MRO determines which method or attribute will be used in case of conflicts.