diamond problem
The question of which method runs when two parent classes share one ancestor.
In more detail
In a diamond, B and C both inherit from A, and D inherits from B and C. Python's method resolution order puts each class before its own parents and keeps parents in their listed order, so D searches D, B, C, A, object, and A appears once. A super() call inside B therefore reaches C for a D object.
Example
class A:
def hi(self): return 'A'
class B(A):
def hi(self): return 'B' + super().hi()
class C(A):
def hi(self): return 'C' + super().hi()
class D(B, C): pass
print(D().hi()) # BCARelated terms
- multiple inheritance — A class inheriting from more than one parent class, searched left to right.
- method resolution order — The order in which Python searches a class and its parents for a method or attribute.
- super() — A built-in that lets a method call the version of itself in the parent class, most often super().__init__(...) in an initialiser.
Taught in
- Inheritance, super() And Polymorphism — PCAP Certified Associate in Python Programming (PCAP-31-03) Exam Prep
- Multiple Inheritance, The MRO And Diamonds — PCAP Certified Associate in Python Programming (PCAP-31-03) Exam Prep
- Special Methods: __str__, __eq__ And Friends — PCAP Certified Associate in Python Programming (PCAP-31-03) Exam Prep
- Object-Oriented Sprint — PCAP Certified Associate in Python Programming (PCAP-31-03) Exam Prep
- Twelve Traps, Mostly Objects — PCAP Certified Associate in Python Programming (PCAP-31-03) Exam Prep