Sub topic 5
Initializing parent state with super().__init__()
This chapter covers how a subclass makes sure its parent's setup code runs. It assumes you can define classes and set instance attributes in __init__. It also assumes you have seen super() used to call a parent method. You should be comfortable with default arguments and with *args and **kwargs.
Why constructors need chaining
Python creates an object and then calls __init__ on it. It calls exactly one __init__: the first one found by attribute lookup on the object's class. If a subclass defines its own __init__, Python does not also call the parent's. The parent's setup is skipped unless you ask for it.
class Base:
def __init__(self):
self.ready = True
class Child(Base):
def __init__(self):
pass # forgot super().__init__()
child = Child()
try:
print(child.ready)
except AttributeError as exc:
print("AttributeError:", exc)Child.__init__ replaces Base.__init__, so ready is never created. The error appears later, wherever the attribute is first read. That is often far from the real mistake.
The fix is to call the parent's initializer explicitly with super().__init__().
The basic pattern
class Vehicle:
def __init__(self, wheels, max_speed):
self.wheels = wheels
self.max_speed = max_speed
class Car(Vehicle):
def __init__(self, brand, max_speed):
super().__init__(wheels=4, max_speed=max_speed)
self.brand = brand
car = Car("Volvo", 180)
print(car.brand, car.wheels, car.max_speed) # Volvo 4 180Car takes a different parameter list from Vehicle. It fills in wheels itself and forwards max_speed. This is allowed. __init__ is not required to have the same signature as the parent's, unlike ordinary methods that callers use polymorphically (see the later chapter on substitutability).
Note that you write super().__init__(...) without self. The zero-argument form of super() already knows the instance and the current class. Writing super().__init__(self, ...) passes self twice and raises a TypeError about too many arguments.
The sequence below shows what happens when you create a Car.
When you do not need to call it
If a subclass does not define __init__ at all, lookup finds the parent's. The subclass then accepts the parent's arguments and the parent's setup runs.
class Animal:
def __init__(self, name):
self.name = name
class Dog(Animal):
def speak(self):
return f"{self.name} barks"
print(Dog("Rex").speak()) # Rex barksYou only need super().__init__() when you write your own __init__. Do not write a subclass __init__ whose only job is to forward the same arguments. It adds code and no behavior.
Where to put the call
Python does not force super().__init__() to be the first line. Its position matters, though.
- Call it first when your own setup depends on the parent's attributes. This is the usual choice.
- Call it later when you must compute or validate something before the parent runs, for example to build an argument for it.
- Never set an attribute before the call if the parent also sets it. The parent will overwrite your value.
class Account:
def __init__(self, balance=0):
self.balance = balance
class BonusAccount(Account):
def __init__(self, balance=0):
self.balance = 100 # set too early
super().__init__(balance) # overwrites it with balance
acct = BonusAccount()
print(acct.balance) # 0, not 100A related trap is a parent __init__ that calls a method the subclass overrides. The overridden version runs on a half-built object.
class Base:
def __init__(self):
self.items = []
self.setup()
def setup(self):
pass
class Child(Base):
def __init__(self):
super().__init__()
self.limit = 5 # assigned after the parent has already called setup()
def setup(self):
print("limit is", self.limit)
try:
Child()
except AttributeError as exc:
print("AttributeError:", exc)Base.__init__ calls self.setup(). Because self is a Child, that runs Child.setup. But limit does not exist yet. To fix this, assign self.limit before calling super().__init__(). A better rule is to avoid calling overridable methods from __init__. If you must, document it, and assign what the override needs before the super() call.
Passing arguments through
A subclass often adds a few parameters and forwards the rest. If the parent's parameter list may change, forwarding with *args and **kwargs keeps the subclass from breaking.
class Employee:
def __init__(self, name, salary):
self.name = name
self.salary = salary
class Manager(Employee):
def __init__(self, *args, reports=None, **kwargs):
super().__init__(*args, **kwargs)
self.reports = list(reports or [])
boss = Manager("Ana", 9000, reports=["Ben", "Cy"])
print(boss.name, boss.salary, boss.reports) # Ana 9000 ['Ben', 'Cy']The keyword-only reports is consumed by Manager. Everything else goes to Employee. The trade-off is that the signature is less visible. Tools and readers cannot see that name and salary are required. Use explicit parameters when the parent's signature is stable and short. Use forwarding when you are wrapping a parent you do not control.
Copy mutable arguments such as reports (list(reports or [])). Otherwise two instances can share one list. Never use a mutable default like reports=[].
Explicit parent calls versus super()
You may see this older style:
class Car(Vehicle):
def __init__(self, brand, max_speed):
Vehicle.__init__(self, 4, max_speed)
self.brand = brandIt works for single inheritance, but it hard-codes the parent's name. If you change the base class, you must edit every call. In multiple inheritance it can run a shared ancestor's __init__ twice or skip a class. Prefer super(). Choose the explicit form only when you deliberately want one specific parent's initializer.
Chaining across several levels
Each class in a chain calls the next one up, so the whole hierarchy initializes from the top down.
class A:
def __init__(self):
print("A init")
self.a = 1
class B(A):
def __init__(self):
print("B init")
super().__init__()
self.b = 2
class C(B):
def __init__(self):
print("C init")
super().__init__()
self.c = 3
obj = C()
print(obj.a, obj.b, obj.c)The output is C init, B init, A init, then 1 2 3. The "init" messages print from the most derived class upward because each prints before delegating. The attributes are assigned in the opposite order: a, then b, then c. If one class in the middle omits its super().__init__() call, every class above it is skipped.
Constructors in multiple inheritance
With multiple bases, super() does not mean "the parent class". It means "the next class in the method resolution order" of the instance's type. For constructors to work, every class in the cooperating group must do two things: accept **kwargs, and pass what it does not use along to super().__init__(**kwargs).
class Named:
def __init__(self, name, **kwargs):
super().__init__(**kwargs)
self.name = name
class Timestamped:
def __init__(self, created, **kwargs):
super().__init__(**kwargs)
self.created = created
class Record(Named, Timestamped):
pass
record = Record(name="report", created="2026-11-26")
print(record.name, record.created) # report 2026-11-26
print([k.__name__ for k in Record.__mro__]) # ['Record', 'Named', 'Timestamped', 'object']Named.__init__ takes name and forwards created onward. Timestamped.__init__ takes created and forwards an empty kwargs to object.__init__(), which accepts no extra arguments. If any class in the chain dropped an argument it did not recognize, the final object.__init__ would raise a TypeError. That error is useful, because it flags a misspelled keyword.
Use keyword arguments here. Positional arguments cannot be routed reliably, because each class does not know which positions the others consume.
Common errors
| Symptom | Likely cause | Fix |
|---|---|---|
| `AttributeError` on a parent attribute | Subclass `__init__` never called `super().__init__()` | Add the call |
| `TypeError: __init__() takes N positional arguments but M were given` | Passed `self` to `super().__init__`, or wrong argument count | Remove `self`, match the parent's signature |
| Value set in subclass is overwritten | Assigned before the `super()` call | Assign after, or pass it as an argument |
| `AttributeError` inside the parent's `__init__` | Parent calls an overridden method that needs attributes not yet set | Set those attributes first, or avoid the call |
| `TypeError` from `object.__init__` | Extra keyword reached the end of the chain | Check spelling and that each class consumes its own arguments |
| A mixin's attributes missing | A class in the MRO did not call `super().__init__()` | Make every cooperating class forward the call |
Checking your work
A quick way to see whether initialization worked is to inspect the instance's __dict__. It lists the attributes actually created.
print(vars(C())) # {'a': 1, 'b': 2, 'c': 3}If an expected key is missing, trace which __init__ in the chain did not run. Reading type(obj).__mro__ shows you the order in which super() will move.
Summary of rules
- If you define
__init__in a subclass, callsuper().__init__(...)unless you intend to replace the parent's setup completely. - Call it with the arguments the parent expects, without
self. - Put it first by default. Assign anything the parent's setup relies on before it.
- Avoid calling overridable methods from
__init__. - In multiple inheritance, use keyword arguments and forward
**kwargsin every class.
Exercise
This code raises an error. Name the error, explain the cause, and fix it. class Shape: def _init(self, color): self.color = color class Circle(Shape): def init_(self, radius): self.radius = radius c = Circle(2) print(c.color)
Show answer
It raises AttributeError because Circle._init replaces Shape.init and never calls it, so color is never set. Fix: give Circle a color parameter and call the parent, for example `def init(self, radius, color): super().init_(color); self.radius = radius, then create it with Circle(2, "red")`.
Exercise
What does this print, and why? class Base: def _init(self): self.level = 1 class Child(Base): def init(self): self.level = 5 super().init_() print(Child().level)
Show answer
It prints 1. Child sets level to 5, then super()._init() runs Base.init_, which sets level back to 1. To keep 5, assign it after the super() call.
Exercise
Two classes, Logged and Cached, each take one keyword argument (logname and cachesize) and both use cooperative super()._init_(**kwargs). Write a class Service(Logged, Cached) that can be created with both. What must each of the two classes do with the arguments it does not use?
Show answer
Service needs no _init of its own, so `Service(logname="app", cachesize=10)` works. Each of Logged and Cached must accept **kwargs and pass them on with super().init(**kwargs) so the other class and finally object.init receive only what is left. Logged takes logname and forwards cachesize to Cached, and Cached takes cachesize and forwards an empty set to object._init_.