Python Multiple Inheritance: Which Parent Method Runs When Names Collide
CiscoSoftware Engineer · OnsiteLast updated
A Python fundamentals question about multiple inheritance in which two parent classes define a method with the same name and a child class inherits from both. It tests the method resolution order, C3 linearization, how super() follows that order, and when composition is the better design.
Two classes each define a method with the same name. A third class inherits from both of them. When that method is called on an instance of the third class, which class's version runs, and why?
class A:
def greet(self):
return "A"
class B:
def greet(self):
return "B"
class C(A, B):
pass
print(C().greet())
What does this program print? What changes if the third class is declared as class C(B, A) instead? Explain the rule Python uses to decide.
Clarifying Questions
- Does the third class inherit from both classes, as in
class C(A, B), or does it receive instances of them and delegate to them? - Does the third class define the method itself, or call
super()anywhere? - Do the two parent classes share a common base class?
Hints
Hint 1
Order of the bases: Look at the order in which the parent classes are listed in the class statement, and predict what happens when you swap them.
Hint 2
Ask the class: Every class can tell you the exact order in which Python searches classes for an attribute. Find out how to print that order.
Follow-up questions
- Both parents define `__init__` and set `self.kw` to different values. What is `C().kw`, and how would you make both initializers run?
- Show a class declaration for which Python refuses to create the class. What error do you get?
- `A.greet` and `B.greet` each call `super().greet()`, and both inherit from a common `Base`. What does `C().greet()` return now?
- When would you prefer composition over multiple inheritance in this situation?
Solution walkthrough is for members
Get the full walkthrough with reference code and complexity analysis, plus Kitty Coach at 300 messages a day. Hints, the code runner and community answers stay free.