Sub topic 4
Extending the Parent Method with super()
This chapter assumes you can define classes, write instance methods that use self, and have read the earlier chapters on subclassing and overriding. You should know that a subclass method with the same name as a parent method replaces it for instances of the subclass.
Replace or extend
An override replaces the parent's method. Often you want more than that: keep the parent's behavior and add something before or after it. You could copy the parent's code into the subclass, but then the two copies drift apart as the parent changes.
super() solves this. Inside a method, super() returns a proxy object. When you look up a method on it, Python searches the classes that come after the current class in the instance's method resolution order (MRO), and it binds the method to the current self. For single inheritance, you can read this as "the parent's version of this method, called on this same object."
class Animal:
def __init__(self, name):
self.name = name
def speak(self):
return f"{self.name} makes a sound"
class Dog(Animal):
def speak(self):
return super().speak() + " loudly"
print(Dog("Rex").speak()) # Rex makes a sound loudlyDog.speak does not rebuild the sentence. It asks Animal.speak for its result and adds to it. If Animal.speak changes later, Dog picks up the change.
What happens during the call
Two details matter here:
- The parent method receives the same
self. It sees the same instance, including any attributes the subclass added. - The parent method's return value comes back to the subclass method. The subclass method decides what to do with it. It can return it unchanged, modify it, or ignore it.
Where to put the super() call
Nothing requires the super() call to be first. Its position decides how the two versions cooperate. There are three common patterns.
Before: parent first, then the subclass adds to the result. The Dog.speak example above works this way.
After a check: the subclass guards the parent. The subclass validates its input, then delegates.
class Account:
def __init__(self, balance):
self.balance = balance
def withdraw(self, amount):
self.balance -= amount
return self.balance
class CheckedAccount(Account):
def withdraw(self, amount):
if amount > self.balance:
raise ValueError("insufficient funds")
return super().withdraw(amount)
acct = CheckedAccount(100)
print(acct.withdraw(30)) # 70
try:
acct.withdraw(500)
except ValueError as exc:
print("Rejected:", exc) # Rejected: insufficient fundsThe guard runs first. If it passes, the parent does the real work. Because the check comes before the super() call, a rejected withdrawal never touches self.balance.
Around: the subclass does work on both sides. Here the subclass records the call and the result.
class Account:
def __init__(self, balance):
self.balance = balance
def withdraw(self, amount):
self.balance -= amount
return self.balance
class AuditedAccount(Account):
def __init__(self, balance):
super().__init__(balance)
self.log = []
def withdraw(self, amount):
self.log.append(f"withdraw {amount} requested")
result = super().withdraw(amount)
self.log.append(f"withdraw {amount} done, balance {result}")
return result
acct = AuditedAccount(100)
acct.withdraw(40)
print(acct.log)
# ['withdraw 40 requested', 'withdraw 40 done, balance 60']AuditedAccount.__init__ also calls super().__init__(balance). The next chapter covers constructor chaining in detail. Here it only shows that super() works the same way for __init__ as for any other method.
Arguments and return values
super().method(...) is an ordinary call. You choose the arguments, and you receive whatever the parent returns.
A subclass often accepts extra arguments that the parent does not know about, or must pass along arguments it does not care about. Forwarding with **kwargs keeps the override working even if the parent's signature gains new options.
class Report:
def render(self, title, *, upper=False):
text = title.upper() if upper else title
return f"Report: {text}"
class TimestampedReport(Report):
def render(self, title, **kwargs):
body = super().render(title, **kwargs)
return f"[2026-11-26] {body}"
print(TimestampedReport().render("sales", upper=True))
# [2026-11-26] Report: SALESIf the subclass needs its own extra parameter, take it by name and forward the rest. A subclass that adds a stamp option could be written like this:
class Report:
def render(self, title, *, upper=False):
text = title.upper() if upper else title
return f"Report: {text}"
class DatedReport(Report):
def render(self, title, *, stamp="2026-11-26", **kwargs):
return f"[{stamp}] " + super().render(title, **kwargs)
print(DatedReport().render("sales", stamp="today", upper=True))
# [today] Report: SALESHow super() works internally
Calling super() with no arguments is shorthand for super(__class__, self), where:
__class__is the class in whose body the method was written. The compiler stores it in a hidden variable when it seessuperused inside a method.selfis the first argument of the method.
You can write the long form yourself, and it behaves the same:
class Animal:
def speak(self):
return "sound"
class Dog(Animal):
def speak(self):
return super(Dog, self).speak() + "!"
print(Dog().speak()) # sound!The first argument names where the search starts: Python looks at type(self).__mro__ and begins with the class after that one. This is why super() is not the same as "the parent class." For a plain chain, the next class is the parent. In a hierarchy with several bases, it can be a sibling. A later chapter on multiple inheritance relies on this behavior.
super() also works in class methods. Python binds the proxy to cls instead of self:
class Shape:
@classmethod
def describe(cls):
return f"shape:{cls.__name__}"
class Circle(Shape):
@classmethod
def describe(cls):
return super().describe() + " (round)"
print(Circle.describe()) # shape:Circle (round)Notice that cls.__name__ inside Shape.describe is Circle. The parent's method ran with the subclass as cls.
super() versus naming the parent
You can also call the parent directly, as in Animal.speak(self). This works, but it has costs.
| Approach | Behavior | Drawback |
|---|---|---|
| `super().speak()` | Finds the next class in the MRO at call time | Only valid inside a method of a class |
| `Animal.speak(self)` | Always calls `Animal`'s version | Breaks if you rename or change the base class, and skips other classes in a multiple-inheritance hierarchy |
Use super() by default. Naming the parent explicitly is a sign that you may be working around a design problem.
Common errors
Forgetting to return the parent's result. The most frequent mistake is calling super() and discarding the value.
class Animal:
def speak(self):
return "sound"
class Dog(Animal):
def speak(self):
super().speak() + " loudly" # result computed, then thrown away
print(Dog().speak()) # NoneThe method has no return, so Python returns None. No error is raised, which makes this easy to miss. Add return.
Calling a method the parent does not have. super().fetch() raises AttributeError: 'super' object has no attribute 'fetch' if no later class in the MRO defines fetch. This often means you meant to call a method on self, or you are overriding a method that does not exist upstream (usually a typo in the name).
Using super() to read instance attributes. Instance attributes live on the object, not on a parent class. Write self.name, not super().name. The super() proxy searches classes, so it finds methods and class attributes, but not per-instance data.
Using super() outside a class body. In a plain function, super() raises RuntimeError: super(): no arguments. Zero-argument super() needs the hidden __class__ variable and a first argument, which only exist in methods defined inside a class. A function attached to a class later does not get them.
Calling super() in a static method. A @staticmethod receives neither self nor cls, so zero-argument super() has nothing to bind to. Redesign it as a class method or pass the class explicitly.
Deciding whether to call super()
Not every override should call the parent. Use this as a rule of thumb:
- Call it when the subclass adds to the parent's behavior, such as extra validation, extra output, logging, or additional state.
- Skip it when the subclass replaces the behavior entirely, and the parent's version would do something wrong or wasteful for the subclass.
- Document it either way. Readers should not have to guess whether skipping the parent was deliberate.
Exercise
Given the code below, what does Cat("Tom").speak() return, and what single change makes it return "Tom makes a sound, purring"?
class Animal:
def _init_(self, name):
self.name = name
def speak(self):
return f"{self.name} makes a sound"
class Cat(Animal):
def speak(self):
super().speak() + ", purring"
Show answer
It returns None, because Cat.speak has no return statement, so the combined string is computed and discarded. Adding return in front of super().speak() + ", purring" makes it return "Tom makes a sound, purring".
Exercise
Write a subclass LoudAccount of the Account class from this chapter whose withdraw(amount) prints "Withdrawing <amount>" before delegating to the parent and returns the parent's result. What does it print and return for LoudAccount(50).withdraw(20)?
Show answer
class LoudAccount(Account): def withdraw(self, amount): print(f"Withdrawing {amount}") return super().withdraw(amount) It prints "Withdrawing 20" and returns 30, because the parent subtracts 20 from the starting balance of 50.