KatInterview

Resolving Name Clashes Across Two Python Parent Classes

Data Structure DesignModel answer
EasyModel answerData Structure Designpythoninheritancemro

Last 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:

  1. What does this program print?
  2. What is printed if the declaration is changed to class Amphibian(Swimmer, Walker)?
  3. State the rule Python uses to choose, and show how you can inspect it at runtime.
  4. Suppose Walker and Swimmer both inherit from a shared base Animal, and each move calls super().move(). Describe the order in which the methods run and why.
  5. 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.