Part 09 / Topic 6 of 12
Multiple inheritance and MRO
A class can have more than one parent: class Child(A, B):. This is multiple inheritance.
When two parents have a method with the same name, Python needs a rule to choose. That rule is the MRO (Method Resolution Order): the order in which Python searches the classes. See it with Class.__mro__ or Class.mro().
Simple rule: the child first, then the parents from left to right, then object.
Think of asking for directions: you ask your friend first, then the shopkeeper, then the police.
Real-world example: a smartphone is both a phone and a camera.
class Phone:
def call(self, number: str) -> str:
return f"Calling {number}"
def info(self) -> str:
return "I am a phone"
class Camera:
def click(self) -> str:
return "Photo saved"
def info(self) -> str:
return "I am a camera"
class SmartPhone(Phone, Camera): # Phone comes first
pass
mobile = SmartPhone()
print(mobile.call("98450 12345")) # Calling 98450 12345
print(mobile.click()) # Photo saved
print(mobile.info()) # I am a phone (Phone is before Camera)
print([c.__name__ for c in SmartPhone.mro()])
# ['SmartPhone', 'Phone', 'Camera', 'object']
Practical advice: keep multiple inheritance for small mixins: tiny classes that add one extra ability (such as "can save to JSON") and are not meant to be used alone. For most other cases, composition (section 11) is clearer.
Full program (inheritance, overriding, mixins and the MRO): examples/03_staff_inheritance.py.
๐ Going deeper:
super()follows the MRO, not just "my parent". In a diamond (D(B, C)whereBandCboth inheritA), callingsuper().__init__()in each class runs every__init__exactly once, in MRO order:D, B, C, A.
Done here? The practice set for Part 9 โ 8 exercises with solutions โ is on the part page.