211. Multiple Inheritance Pitfalls
πΉ 1. Diamond Problem β Ambiguity in Method Resolution Order (MRO)
Copy
class A:
def greet(self):
print("Hello from A")
class B(A):
pass
class C(A):
def greet(self):
print("Hello from C")
class D(B, C):
pass
d = D()
d.greet() # Hello from C
print(D.mro()) # [D, B, C, A, object]π Issue:
Dinherits from bothBandC, butCoverridesgreet.Method Resolution Order (MRO) determines that
C's method is called.
πΉ 2. MRO Conflicts β Inconsistent Hierarchy
Copy
π Issue:
The MRO becomes inconsistent when
DandEhave different base class orders.
πΉ 3. Super() Calls in Multiple Inheritance
Copy
π Issue:
Calls
super()correctly based on MRO:
Copy
This works if all classes use
super()correctly.
πΉ 4. Using super() Incorrectly
super() IncorrectlyCopy
π Issue:
Copy
A.__init__()gets called twice!Fix this by using
super()only if all classes cooperate.
πΉ 5. Attribute Name Conflicts
Copy
π Issue:
Both
AandBdefinevalue.MRO picks
Aβs version, potentially leading to bugs.
πΉ 6. Overriding Methods in Unexpected Ways
Copy
π Issue:
The method in
Cis ignored becauseBcomes first inD(B, C).
πΉ 7. Calling Parent Methods Explicitly
Copy
π Issue:
Copy
Bad practice: Calls
A.show()twice.Better to use
super()to avoid redundant calls.
πΉ 8. Using isinstance with Multiple Base Classes
isinstance with Multiple Base ClassesCopy
π Issue:
isinstance(d, A)is True, even thoughDnever explicitly inherits fromA.
πΉ 9. Multiple Base Classes with super()
super()Copy
π Correct MRO prevents double initialization:
Copy
Ensure all classes use
super()correctly to prevent duplicate calls.
πΉ 10. Avoiding Multiple Inheritance with Composition
Copy
π Why this works better?
Composition over inheritance avoids MRO issues.
More maintainable & modular than multiple inheritance.
π Summary
Pitfall
Issue
Solution
Diamond Problem
MRO ambiguity
Use super() properly
MRO Conflicts
Inconsistent ordering
Follow a clear class hierarchy
Super Calls
Wrong method calls
Ensure all classes use super()
Attribute Conflicts
Overwritten attributes
Use unique attribute names
Method Overriding
Unexpected behavior
Check mro() before overriding
Explicit Parent Calls
Repeating method calls
Use super() instead
isinstance Issues
Inheriting unintended behavior
Avoid unnecessary multiple inheritance
Multiple __init__ Calls
Calls parent multiple times
Use super() correctly
Super in Multiple Base Classes
Wrong super() order
Use cooperative multiple inheritance
Alternative: Composition
Complex MRO issues
Prefer composition over inheritance
π Best Practices
β
Prefer single inheritance unless multiple inheritance is absolutely needed. β
Use MRO (print(Class.mro())) to check method resolution order. β
Always use super() to avoid redundant method calls. β
Consider composition as an alternative.
Last updated