Back
+15 XP
Concept

Multiple Inheritance & Method Resolution Order (MRO)

Python supports multiple inheritance: `class C(A, B):`. It resolves method conflicts using C3 Linearization, inspectable via `Class.mro()`.

python
class Flyer:
    def act(self):
        return "Flying"

class Swimmer:
    def act(self):
        return "Swimming"

class Duck(Flyer, Swimmer):
    pass

d = Duck()
print(d.act())  # Flying (Flyer is searched first!)

# 3. Multiple Inheritance & Method Resolution Order (MRO) Python supports multiple inheritance: `class C(A, B):`. It resolves method conflicts using C3 Linearization, inspectable via `Class.mro()`: ```python class Flyer: def act(self): return "Flying" class Swimmer: def act(self): return "Swimming" class Duck(Flyer, Swimmer): pass d = Duck() print(d.act()) # Flying (Flyer is searched first!) ``` When you call a method, Python searches the class hierarchy strictly in the order returned by `Duck.mro()`: `[Duck, Flyer, Swimmer, object]`. The first match wins.

Checkpoint

In `class C(A, B):`, if both `A` and `B` implement `run()`, which one gets executed when calling `C().run()`?

Practice

Inspect the MRO of a class `RobotCat(Machine, Pet)` where both are empty base classes. Print the class name of the first entry in `RobotCat.mro()`.

Terminal
01
Tap code blocks below to assemble
Available Blocks