Sub topic 4
Extending the parent method with super()
This chapter assumes you can define classes, write instance methods using self, and have already seen a subclass override a parent method. Here you will learn how to extend a parent method instead of replacing it.
Why override and still call the parent
Overriding a method replaces the parent's version for instances of the subclass. Often you don't want to throw the parent's work away. You want to run it and then add to it. super() returns a proxy object that looks up attributes starting after the current class in the method resolution order, so super().speak() calls the parent's speak() on the same instance.
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.speak()) # Rex makes a sound loudlyDog.speak() does not copy the parent's code. It calls it, then changes the result. If Animal.speak() is later improved, Dog gets the improvement for free.
What super() does
In Python 3, super() with no arguments works inside a method. It uses two things: the class where the method is defined, and the instance (self). It then finds the next class after the current one in type(self).__mro__ and looks the name up there. The returned method is already bound to self, so you don't pass self yourself.
The diagram below shows the call order for dog.speak().
Where to place the super() call
The position of the call decides the order of the work.
- Call first, then add: the parent's work runs before yours. This is common in
__init__, because your code may rely on attributes the parent sets. - Add first, then call: your code runs before the parent's. Use this for checks or setup the parent should see.
- Wrap the call: do work before and after, such as logging around a save.
You can also use the parent's result, change it, or ignore it. The choice is yours, as long as it is deliberate.
Common mistakes
- Calling the parent by name with the wrong arguments.
Animal.speak()withoutselfraises aTypeError.super().speak()passesselffor you. - Forgetting to return the parent's result. If you write
super().speak()and thenreturn "loud", the parent's value is discarded. - Changing the signature. If the parent's method takes
(self, name)and your override takes different arguments, any code that calls it through the parent type may break. Chapter 12 covers this. - Using
super()outside a method. Zero-argumentsuper()fails at module level or in a plain function withRuntimeError: super(): no arguments.
class Animal:
def speak(self):
return "sound"
class Dog(Animal):
def speak(self):
super().speak() # result is discarded
return "bark"
print(Dog().speak()) # barkPassing arguments through
When a subclass adds no new parameters, you can forward everything to the parent with *args and **kwargs. This keeps the override working if the parent's signature changes.
class Logger:
def log(self, message, level="info"):
return f"[{level}] {message}"
class TimestampLogger(Logger):
def log(self, *args, **kwargs):
return "12:00 " + super().log(*args, **kwargs)
print(TimestampLogger().log("started", level="debug"))
# 12:00 [debug] startedExercise
Given class Base: def total(self): return 10 and class Child(Base): def total(self): return ???, what expression in ??? makes Child().total() return 15 without writing the number 10?
Show answer
super().total() + 5. It calls Base.total() on the same instance, which returns 10, then adds 5.
Exercise
A subclass overrides save(self) and calls super().save() on the last line but forgets return. The parent's save returns True. What does the caller of the subclass's save() receive, and how do you fix it?
Show answer
The caller receives None, because the subclass method has no return statement. Fix it by writing return super().save().