In this lesson, you will learn how to use the super() function to keep the original functionality of a parent method while extending it with new logic in your child class.
Why use super()?
When you override a method in a child class, you completely replace the parent's version of that method. Sometimes, however, you don't want to replace it entirely; you want to "borrow" the parent's work and then add your own code on top of it. This is where super() comes in. It acts as a temporary bridge, allowing your child class to reach back and execute the parent’s method logic.
A Concrete Illustration
Imagine we are building a simple game. We have a base Character class and a Hero subclass.
class Character:
def greet(self):
print("Hello! I am a character.")
class Hero(Character):
def greet(self):
# First, run the parent logic
super().greet()
# Then, add the specific hero logic
print("I am here to save the day!")
my_hero = Hero()
my_hero.greet()
When you call my_hero.greet(), Python does two things:
- It enters the
Heroclass, but seessuper().greet(). This tells Python: "Go find thegreetmethod in the parent class and run it first." - After the parent finishes printing its message, the program returns to the child class to finish the remaining lines, printing the hero-specific message.
Avoiding Redundancy
Without super(), you would have to copy-paste the parent's code into your child class if you wanted to maintain that behavior. This creates "spaghetti code" that is hard to maintain. If you ever needed to update the greet logic in the base Character class, you would have to hunt down every single child class and update them manually. By using super(), you ensure that the Hero always stays in sync with the base Character behavior, while still being allowed to perform its own unique actions.
Key Takeaway: The super() function allows a child class to call a parent’s method, ensuring you can extend existing functionality without losing the original logic.