Sub topic 9
Cooperating with parents: super() and the MRO
This chapter assumes you can define classes, write __init__, and build a simple subclass that overrides a method, as covered in the inheritance chapter. You should also be comfortable with *args and **kwargs. By the end you will know what super() does, how Python orders parent classes, and how to write __init__ methods that work under multiple inheritance.
Why call the parent at all
A subclass often extends its parent's behavior instead of replacing it. The usual case is __init__. The parent sets up some attributes, and the child adds its own.
class Animal:
def __init__(self, name):
self.name = name
class Dog(Animal):
def __init__(self, name, tricks=None):
super().__init__(name)
self.tricks = list(tricks or [])
rex = Dog("Rex", ["sit"])
print(rex.name, rex.tricks) # Rex ['sit']If Dog.__init__ did not call the parent, self.name would never be set. Python does not call parent initializers for you once a subclass defines its own __init__. A missing super().__init__(...) call is one of the most common inheritance bugs, and it usually shows up later as an AttributeError.
What super() actually does
super() does not mean "my parent class". It returns a proxy object that looks up attributes in the classes that come after the current class in the instance's method resolution order (MRO). The MRO is the linear list of classes Python searches, in order, when you access an attribute on an instance.
You can inspect it with __mro__:
class A: pass
class B(A): pass
print([c.__name__ for c in B.__mro__]) # ['B', 'A', 'object']Inside a method, the zero-argument form super() is shorthand for super(__class__, self). Here __class__ is the class where the method was written, and self is the current instance. The lookup starts just after __class__ in the MRO of type(self). That detail matters under multiple inheritance, because the next class in line is not always the parent you wrote in the class statement.
The MRO and the diamond
With single inheritance the MRO is just the chain of parents. With multiple inheritance, Python computes it with the C3 linearization algorithm. You don't need to run the algorithm by hand. These are its guarantees:
- A class always appears before its parents.
- The order in which you list bases in the
classstatement is preserved. - Every class appears exactly once.
The classic case is the diamond: two classes inherit from one base, and a fourth inherits from both.
The arrows point from parent to child. The MRO of D is D, B, C, A, object. Each class below calls super().hello() and adds its own name:
class A:
def hello(self):
return ["A"]
class B(A):
def hello(self):
return ["B"] + super().hello()
class C(A):
def hello(self):
return ["C"] + super().hello()
class D(B, C):
def hello(self):
return ["D"] + super().hello()
print(D().hello()) # ['D', 'B', 'C', 'A']
print([k.__name__ for k in D.__mro__]) # ['D', 'B', 'C', 'A', 'object']Look at what happens inside B.hello. Its written parent is A, but super() there resolves to C, because C follows B in the MRO of a D instance. The same B.hello called on a plain B instance would go straight to A. super() depends on the instance's class, not only on where the code is written.
Why naming the parent explicitly breaks down
Before super() was common, people wrote Parent.__init__(self). In a diamond, this runs shared ancestors more than once:
class Base:
def __init__(self):
print("Base")
class Left(Base):
def __init__(self):
Base.__init__(self)
print("Left")
class Right(Base):
def __init__(self):
Base.__init__(self)
print("Right")
class Bottom(Left, Right):
def __init__(self):
Left.__init__(self)
Right.__init__(self)
print("Bottom")
Bottom()
# Base
# Left
# Base
# Right
# BottomBase initializes twice. If Base.__init__ opened a file or registered the object somewhere, that would be a real bug. Replace every explicit call with super().__init__() and the output becomes Base, Right, Left, Bottom. Each class runs once, following the MRO Bottom, Left, Right, Base.
Explicit calls also hard-code the hierarchy. If you later insert a class between Left and Base, every explicit call has to be edited. super() follows the MRO and needs no edits.
Writing cooperative __init__ methods
Classes in a multiple-inheritance hierarchy cooperate when each one does three things:
- Takes the arguments it needs by name, and passes the rest along with
**kwargs. - Calls
super().__init__(**kwargs)exactly once. - Does not assume which class comes next.
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 30
print([c.__name__ for c in Person.__mro__])
# ['Person', 'Named', 'Aged', 'object']Person has no __init__, so Python finds Named.__init__ first in the MRO. Named takes name, forwards age to Aged through super(), and Aged forwards the now-empty kwargs to object.__init__. object.__init__ accepts no extra arguments, so a leftover keyword causes a TypeError. That behavior is useful, because a typo such as Person(name="Ana", agee=30) fails loudly instead of being ignored.
Keyword arguments are the practical choice here. Positional arguments depend on the order of the MRO, which is hard to keep track of across several classes.
Where to place the super() call
The position of super().__init__() inside your method is a design choice:
- Call it first when the parent must set up state your code relies on. This is the usual choice.
- Call it last when you need to prepare values before the parent sees them.
- In cooperative classes like
Namedabove, calling it first means the whole chain is initialized before each class assigns its own attribute.
Whichever you choose, keep it consistent and document it if subclasses might depend on it.
super() beyond __init__
super() works for any method, including classmethods. Inside a classmethod it uses cls instead of self:
class Config:
@classmethod
def defaults(cls):
return {"debug": False}
class DevConfig(Config):
@classmethod
def defaults(cls):
base = super().defaults()
base["debug"] = True
return base
print(DevConfig.defaults()) # {'debug': True}Here is where super() is not available or is awkward:
- A
@staticmethodreceives neitherselfnorcls, so zero-argumentsuper()fails with aRuntimeError. Call the parent by name or make the method a classmethod. - A function defined outside a class body has no
__class__, so zero-argumentsuper()does not work there. - Special methods that return
NotImplemented, such as__eq__, need care.super().__eq__(other)may returnNotImplemented, and you should pass that result through instead of treating it as a boolean.
Common errors
| Symptom | Cause | Fix |
|---|---|---|
| `AttributeError` for a parent attribute | Subclass defined `__init__` but never called `super().__init__()` | Add the call |
| `TypeError` about unexpected arguments from `object.__init__` | An argument was passed along the chain that no class consumed | Check argument names, and make sure every class consumes its own |
| Shared ancestor runs twice | Explicit `Parent.__init__(self)` calls in a diamond | Use `super()` everywhere |
| `TypeError: Cannot create a consistent method resolution order` | Base order contradicts the hierarchy | Reorder the bases |
| `RuntimeError: super(): no arguments` | Zero-argument `super()` used in a staticmethod or plain function | Use a classmethod, or name the class |
The inconsistent-MRO error appears at class creation time. It happens when you list a class before one of its own subclasses:
class X: pass
class Y(X): pass
try:
class Z(X, Y):
pass
except TypeError as exc:
print(exc)
# Cannot create a consistent method resolution order (MRO) for bases X, YX, Y asks Python to put X before Y, but Y is a subclass of X and must come first. Writing class Z(Y, X) fixes it.
Decision criteria
Use plain super().__init__(...) with explicit arguments when you have single inheritance. It is the simplest form, and its meaning is clear.
Use the cooperative **kwargs style when classes are designed to be combined, such as small mixins that each add one capability. All the classes involved should be written by you or follow the same convention.
Consider composition instead when you find yourself reasoning about the MRO for more than a moment. If a reader cannot predict the call order without running __mro__, the hierarchy is probably too clever. The composition chapter covers that alternative.
Exercise
Given the classes below, what does print(Z().who()) print, and what is the MRO of Z?
class P:
def who(self):
return ["P"]
class Q(P):
def who(self):
return ["Q"] + super().who()
class R(P):
def who(self):
return ["R"] + super().who()
class Z(R, Q):
def who(self):
return ["Z"] + super().who()
Show answer
The MRO is Z, R, Q, P, object, because the bases are searched in the order listed and P must come after both Q and R. The output is ['Z', 'R', 'Q', 'P']. Inside R.who, super() resolves to Q (the next class in Z's MRO), not P.
Exercise
Why does Bottom.__init__ in the explicit-call example print "Base" twice, and how do you change the code so "Base" prints once?
Show answer
Left._init and Right.init each call Base.init directly, and Bottom calls both of them, so Base runs once per path through the diamond. Replace every explicit parent call with super().init() in Left, Right, and Bottom, and make Base's init_ the end of the chain. Python then follows the MRO Bottom, Left, Right, Base and runs each class exactly once.