Sub topic 9
Cooperating with parents: super() and the MRO
This chapter assumes you can define classes, write __init__, and override methods through basic inheritance. Here you will see what super() does, how Python decides which method to run, and where multiple inheritance goes wrong.
Calling the parent with super()
A subclass that defines __init__ replaces the parent's __init__. If the parent sets up attributes, the subclass must call it explicitly.
class Animal:
def __init__(self, name):
self.name = name
def speak(self):
return "..."
class Dog(Animal):
def __init__(self, name, tricks=None):
super().__init__(name)
self.tricks = list(tricks or [])
def speak(self):
return "Woof"
rex = Dog("Rex", ["sit"])
print(rex.name, rex.tricks) # Rex ['sit']
print(Dog.__mro__)super() returns a proxy that looks up a method starting after the current class in the method resolution order. You do not pass self, because the proxy is already bound to the instance.
The method resolution order
The method resolution order (MRO) is the list of classes Python searches, in order, when you access an attribute on an instance. Every class stores it in __mro__. For Dog it is Dog, Animal, object. The first class in the list that defines the name wins.
super() does not mean "my parent". It means "the next class after this one in the MRO of the instance's actual type". With single inheritance the two are the same. With multiple inheritance they can differ.
Multiple inheritance and the diamond
When two parents share a base class, the layout is called a diamond. Python computes the MRO with the C3 linearization algorithm. It keeps each class before its parents and keeps the order in which you listed the bases.
class Base:
def hello(self):
print("Base")
class Left(Base):
def hello(self):
print("Left")
super().hello()
class Right(Base):
def hello(self):
print("Right")
super().hello()
class Child(Left, Right):
def hello(self):
print("Child")
super().hello()
Child().hello()
print([c.__name__ for c in Child.__mro__])This prints Child, Left, Right, Base, then ['Child', 'Left', 'Right', 'Base', 'object']. Inside Left, super().hello() calls Right, not Base. Left has no direct link to Right. The MRO of Child puts Right next. Because every class calls super(), Base runs exactly once.
Cooperative classes
Multiple inheritance works when every class in the chain calls super() and accepts arguments it does not use. A common pattern is to pass unknown keyword arguments along.
class Named:
def __init__(self, name, **kwargs):
super().__init__(**kwargs)
self.name = name
class Aged:
def __init__(self, age, **kwargs):
super().__init__(**kwargs)
self.age = age
class Person(Named, Aged):
pass
p = Person(name="Ana", age=30)
print(p.name, p.age) # Ana 30Named hands age on to Aged without knowing that Aged exists. The last super().__init__() reaches object.__init__ with no arguments, which is correct.
Common errors
- Calling a parent by name in a diamond.
Base.hello(self)skips the MRO, soBasemay run twice or a sibling may be skipped. Usesuper()throughout. - Forgetting to call
super().__init__(). The parent's attributes are never set, and you get anAttributeErrorlater. - Mixing styles. If one class in the chain does not call
super(), the classes after it in the MRO never run. - Inconsistent base order.
class C(Base, Left)raisesTypeError: Cannot create a consistent method resolution order, becauseBasecannot come before its own subclassLeft.
Exercise
In the diamond example, Left.hello calls super().hello(). Which class's hello runs next when you call Child().hello(), and why is it not Base?
Show answer
Right.hello runs next. super() follows the MRO of the instance's type, Child, which is Child, Left, Right, Base, object. The class after Left in that list is Right.