Resolving Name Clashes Across Two Python Parent Classes
Data Structure DesignModel answerLast updated
Predict which inherited method runs when a class has two parents defining the same method name, and explain Python's lookup order, super() cooperation, and alternatives.
Two unrelated Python classes each provide a method with an identical name. A third class lists both of them as parents. When you call that method on an instance of the third class, only one implementation can execute.
class Walker:
def move(self):
return "walk"
class Swimmer:
def move(self):
return "swim"
class Amphibian(Walker, Swimmer):
pass
print(Amphibian().move())
Answer the following:
- What does this program print?
- What is printed if the declaration is changed to
class Amphibian(Swimmer, Walker)? - State the rule Python uses to choose, and show how you can inspect it at runtime.
- Suppose
WalkerandSwimmerboth inherit from a shared baseAnimal, and eachmovecallssuper().move(). Describe the order in which the methods run and why. - When does Python refuse to create a class with multiple parents, and what alternatives to multiple inheritance would you consider?
Assume the third class does not define move itself unless stated otherwise.
Hints
Hint 1
Python does not search parents arbitrarily. Each class has a single, deterministic ordered list of classes that attribute lookup walks through, and the order in the `class` line matters.
Hint 2
Print `Amphibian.__mro__` (or call `Amphibian.mro()`) to see the list. The first class in it that defines the name wins.
Hint 3
`super()` does not mean 'my parent'. It means 'the next class after me in the MRO of the instance's type', which is why it can reach a sibling class in a diamond.
Model answer
Easy Try it yourself first — then compare your approach, complexity and edge cases.
Short answer
class Amphibian(Walker, Swimmer)printswalk.class Amphibian(Swimmer, Walker)printsswim.
Python resolves attribute lookups through the method resolution order (MRO), an ordered list of classes computed once per class. The lookup walks that list and uses the first class that defines the name. Parents are listed left to right, so the leftmost parent wins when nothing else intervenes.
Inspecting the order
print(Amphibian.__mro__)
# (<class 'Amphibian'>, <class 'Walker'>, <class 'Swimmer'>, <class 'object'>)
Amphibian.mro() returns the same thing as a list. Swimmer.move is not deleted or overridden; it is merely hidden behind Walker.move in the list. You can still call it explicitly with Swimmer.move(self).
How the order is computed: C3 linearization
Python uses the C3 algorithm. The MRO of a class is the class itself followed by a merge of the MROs of its parents and the list of the parents themselves. The merge repeatedly takes the first head that does not appear in the tail of any other list. This guarantees:
- Children before parents. A class always appears before any of its bases.
- Local precedence. The left-to-right order of bases in the
classstatement is preserved. - Monotonicity. If class X comes before Y in the MRO of some parent, it still does in the MRO of the child.
- Each class appears once, with
objectlast.
Cooperative super() and the diamond
class Animal:
def move(self):
return ["animal"]
class Walker(Animal):
def move(self):
return ["walk"] + super().move()
class Swimmer(Animal):
def move(self):
return ["swim"] + super().move()
class Amphibian(Walker, Swimmer):
pass
print(Amphibian().move()) # ['walk', 'swim', 'animal']
print(Amphibian.__mro__) # Amphibian, Walker, Swimmer, Animal, object
Inside Walker.move, super() resolves to the next class after Walker in the MRO of the instance's class, which is Swimmer, not Animal. Animal is placed after both of its children, so it runs exactly once, at the end. A naive depth-first search would find Animal right after Walker and run it before Swimmer, which is why Python does not use plain DFS.
The same applies to __init__. If every class in the chain calls super().__init__(**kwargs) and passes along what it does not consume, each initializer runs once. If one class hardcodes Walker.__init__(self) instead, Swimmer.__init__ can be skipped or Animal.__init__ can be run twice.
When Python refuses
If the base orders cannot be reconciled, class creation fails with a TypeError:
class X: pass
class Y(X): pass
class Z(X, Y): pass # TypeError: Cannot create a consistent MRO
Z demands X before Y, but Y is a subclass of X and must come first. The fix is to reorder: class Z(Y, X).
Trade-offs and alternatives
- Explicit call:
Swimmer.move(self)is simple for one-off cases but bypasses the MRO and breaks cooperative chains. - Mixins: small classes with no state of their own, one narrow behavior, placed to the left of the main base (
class Service(LoggingMixin, Base)). Keep method names distinct to avoid clashes. - Composition: give the class a
Walkerand aSwimmeras attributes and delegate explicitly. This is usually the better design when the two behaviors are independent, because the choice of whichmoveis used is visible in the code rather than implied by base order. - Rename or adapt: if both methods must be exposed, define
walk()andswim()and avoid the clash entirely.
Common mistakes
- Believing the last listed parent wins, or that Python raises an error on any name clash. It does not; the clash is resolved silently, which is also the risk.
- Treating
super()as "the direct parent". It follows the MRO of the instance, so its target can change when a class is subclassed. - Mixing
super()with hardcodedParent.method(self)calls in the same hierarchy. - Forgetting that the MRO is a property of the most derived class, so the same method can call different
super()targets in different subclasses. - Not accepting
*args, **kwargsin cooperative__init__methods, so an unexpected argument breaks the chain.
Complexity
MRO computation happens once at class creation and is cheap for realistic hierarchies. Each attribute lookup is a linear scan of the MRO in the worst case, but CPython caches results via a type attribute cache, so the cost in practice is negligible.