The diamond problem shows what happens when a class inherits from two classes that share a common ancestor. It helps us understand how Python decides which method to use.
Diamond problem in Python
class A: def method(self): print("A method") class B(A): def method(self): print("B method") class C(A): def method(self): print("C method") class D(B, C): pass
Python uses a method resolution order (MRO) to decide which method to call.
The order of inheritance in the class definition matters for MRO.
class A: def greet(self): print("Hello from A") class B(A): def greet(self): print("Hello from B") class C(A): def greet(self): print("Hello from C") class D(B, C): pass obj = D() obj.greet()
class A: def greet(self): print("Hello from A") class B(A): def greet(self): print("Hello from B") class C(A): def greet(self): print("Hello from C") class D(C, B): pass obj = D() obj.greet()
This program creates a diamond shape in inheritance: D inherits from B and C, both inherit from A. When calling show on D, Python uses B's method because B is first in the inheritance list. The MRO print shows the order Python follows to find methods.
class A: def show(self): print("Method in A") class B(A): def show(self): print("Method in B") class C(A): def show(self): print("Method in C") class D(B, C): pass obj = D() obj.show() print(D.__mro__)
Python solves the diamond problem using the C3 linearization algorithm for MRO.
Always check the MRO with ClassName.__mro__ to understand method lookup order.
Changing the order of base classes changes which methods are used.
The diamond problem happens when multiple inheritance creates a diamond shape in the class tree.
Python uses method resolution order (MRO) to decide which method to call.
The order of base classes in the class definition affects which method is chosen.