Several parents: multiple inheritance and the MRO
🌍 In real life. A duck walks, flies and swims; a smartphone is a phone and a camera. Sometimes a class really is two things at once. Python lets a class name several parents: class Duck(Flyer, Swimmer). That raises one question: when both parents have a move, which one does a duck use?
The idea in one sentence: with several parents, Python still searches one fixed list of classes, the MRO (method resolution order), and you can see it with Duck.__mro__.
Its words:
- multiple inheritance: a class with more than one parent
- MRO: the order Python searches for a name: the object's class, then the rest of the family, each class once
- C3 rule: how Python builds the MRO: every class comes before its own parents, and parents keep the order they are listed in
- mixin: a small class that only adds one ability (like
to_json), meant to be mixed into others
How Python builds the MRO for Duck(Flyer, Swimmer), step by step:
- start with Duck
- take Flyer's own line (Flyer, Animal) and Swimmer's (Swimmer, Animal), keeping Flyer before Swimmer
- Flyer goes next; Animal must wait, because Swimmer, one of its children, still hasn't been placed
- then Swimmer, then Animal (and
object, the root of every class)
Result: Duck, Flyer, Swimmer, Animal. Watch the lookups climb in that order:
Why this order. Look at d.hello: Flyer inherits from Animal, yet Python checks Swimmer before Animal. If it went straight up from Flyer to Animal, Animal's general hello would hide Swimmer's more specific one, and Swimmer's version could never be used. The C3 rule makes sure a class always comes before its parents, so a child's version always wins over the one it was built from.
super() follows the MRO too. It doesn't mean "my parent"; it means "the next class in this object's MRO". So when every class passes the work on with super(), each one runs exactly once, in MRO order. Below, Flyer's super() leads to Swimmer, not to Animal:
class Animal:
def intro(self):
return ["animal"]
class Flyer(Animal):
def intro(self):
return ["flyer"] + super().intro()
class Swimmer(Animal):
def intro(self):
return ["swimmer"] + super().intro()
class Duck(Flyer, Swimmer):
def intro(self):
return ["duck"] + super().intro()
print([c.__name__ for c in Duck.__mro__])
print(Duck().intro())Mixins: the most common use. A mixin adds one ability and nothing else: no __init__, no data of its own. Put it first in the list, so its methods are found before the main parent's. Here vars(self) gives an object's attributes as a dict, and json.dumps (Chapter 20) turns that into text:
import json
class JsonMixin:
def to_json(self):
return json.dumps(vars(self))
class Item:
def __init__(self, name, price):
self.name = name
self.price = price
class Book(JsonMixin, Item):
pass
print(Book("Python Basics", 450).to_json())Mistakes and edge cases.
- an order that can't exist:
class Bat(Animal, Flyer)puts Animal before its own child Flyer, which breaks the C3 rule, so Python refuses the class with a TypeError ("Cannot create a consistent method resolution order"); list the child first - reading
super()as "my parent": in a family with several parents it calls the next class in the MRO, which may be a sibling - calling a parent directly (
Animal.intro(self)) instead ofsuper(): some classes can be skipped (like Right in the last task), and if a class calls both parents itself, a shared parent runs twice - mixins with their own
__init__and data: they start to fight over who sets what; keep them small - reaching for it too often: composition (Lesson 22.4) is usually simpler; multiple inheritance shines for small mixins
Quiz
What does this print?
class A: pass class B: pass class C(A, B): pass print([k.__name__ for k in C.__mro__])What does this print?
class A: def hi(self): return "A" class B: def hi(self): return "B" class C(B, A): pass print(C().hi())What does this print?
class Base: def name(self): return "base" class Left(Base): def name(self): return "left>" + super().name() class Right(Base): def name(self): return "right>" + super().name() class Both(Left, Right): pass print(Both().name())What is a mixin?
- A small class that adds one ability to other classes, with no data of its own
- A class with no parents
- Two objects joined into one
Python refuses this program with a TypeError. Which line is wrong?
class Animal: pass class Flyer(Animal): pass class Bat(Animal, Flyer): pass
Coding tasks
Animal,FlyerandSwimmerare written for you. Writeclass Duckthat inherits from bothFlyerandSwimmer, in the order that makesDuck().move()give"fly". A duck must still be able toswim().Personis written for you. Write a mixinGreetMixinwith one method,greet(), returning"Hi, I'm "followed byself.name(no__init__). Then writeclass Studentthat mixes it intoPerson, mixin first.Base.tags()returns["base"]. FixLeftandRightso each adds its own tag and then passes on withsuper(), so thatBoth().tags()gives["left", "right", "base"].