Sub topic 5
Initializing parent state with super().__init__()
This chapter assumes you can define classes, write __init__ with self, and have read the earlier chapters on subclasses and method overriding. Here you will see why a subclass constructor has to call its parent's constructor, and how to do it correctly.
Why the parent constructor does not run for you
__init__ is an ordinary method, so overriding it follows the same rule as any other override. If a subclass defines __init__, Python uses that one and never looks up the parent's. The parent's setup code is skipped unless you call it yourself.
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() runs without error. The failure appears later, when other code reads child.ready. This delay makes the bug hard to trace.
If the subclass does not define __init__ at all, lookup finds Base.__init__ and runs it. The problem only exists when you override the constructor.
Calling the parent with super().__init__()
Inside a method, super() returns a proxy that looks up names starting after the current class in the method resolution order. For a single parent, that means the parent class. Call super().__init__(...) and pass whatever arguments the parent constructor expects. Do not pass self, because super() binds it for you.
class Animal:
def __init__(self, name):
self.name = name
def speak(self):
return f"{self.name} makes a sound"
class Dog(Animal):
def __init__(self, name, breed):
super().__init__(name)
self.breed = breed
def speak(self):
return super().speak() + " loudly"
dog = Dog("Rex", "Labrador")
print(dog.name, dog.breed) # Rex Labrador
print(dog.speak()) # Rex makes a sound loudlyDog.__init__ takes name and breed. It hands name to Animal.__init__, which sets self.name, and then sets self.breed itself. Both attributes end up on the same object.
Where to place the call
Python does not force the call to come first, but putting it first is the safe default. The parent's setup then finishes before your subclass code uses it.
Place it later only when you have a reason. One example is computing a value to pass up:
class Account:
def __init__(self, owner, balance):
self.owner = owner
self.balance = balance
class SavingsAccount(Account):
def __init__(self, owner, deposit, rate):
opening = max(deposit, 0)
super().__init__(owner, opening)
self.rate = rate
acct = SavingsAccount("Ana", -50, 0.02)
print(acct.owner, acct.balance, acct.rate) # Ana 0 0.02Here the subclass cleans the input before the parent sees it. Avoid reading attributes the parent sets before the call has run. For example, using self.balance before super().__init__ would raise AttributeError.
Common mistakes
- Forgetting the call. Parent attributes are missing, as in the
Childexample above. - Wrong arguments.
super().__init__()with no arguments fails withTypeErrorif the parent requiresname. The subclass signature must supply everything the parent needs. - Passing
selfexplicitly.super().__init__(self, name)sendsselftwice and raisesTypeErroror silently misassigns arguments. - Hardcoding the parent.
Animal.__init__(self, name)works for one parent but breaks cooperative multiple inheritance, covered in a later chapter. Prefersuper().
Summary of the rule
When you override __init__, decide explicitly what to do with the parent's constructor. Almost always, call super().__init__(...) with the arguments it needs, before your own setup.
Exercise
Given the classes below, what happens when you run Cat("Tom").lives, and how do you fix it?
class Pet:
def _init(self, name):
self.name = name
class Cat(Pet):
def init_(self, name):
self.lives = 9
Show answer
It raises no error at construction, but Cat("Tom").lives returns 9 while Cat("Tom").name raises AttributeError, because Pet._init never ran. Fix it by adding `super().init(name)` as the first line of Cat.init_.
Exercise
Why does super().__init__(self, name) fail inside a subclass constructor?
Show answer
super() already binds self to the parent's method, so passing self again supplies an extra positional argument. Python then raises TypeError because Animal._init receives too many arguments. Write `super().init_(name)`.