Python Multiple Inheritance: Which Parent Method Runs When Names Collide
Company: Cisco
Role: Software Engineer
Category: Software Engineering Fundamentals
Difficulty: easy
Interview Round: Onsite
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?
```python
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.
```hint 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 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.
```
### 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?
### What a Strong Answer Covers
- The correct output for the given base order and for the swapped order
- The lookup rule (the method resolution order), how to inspect it, and the properties of the C3 linearization behind it
- How `super()` follows that order, including in a diamond and in `__init__`
- When Python refuses to build the order, and alternatives such as explicit calls, mixins or composition
### 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?
Overview: 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.
Read the full Cisco Software Engineer interview experience this question came from