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())   # BCA

Related terms

Taught in

References

Certification courses