When working with inheritance in Python, you’ll often see the super()
function.
But what does it really do? Why not just call the parent class directly?
In this short, practical guide, you’ll learn:
- What
super()
is - Why and when you should use it
- How it helps you reuse and extend code from parent classes
- Common mistakes beginners make
- Real examples that make it click
Let’s get into it.
🧠 What is super()
?
super()
is a built-in Python function used inside a child class to refer to the parent class specifically, to access its methods.
Instead of writing:
Python
ParentClass.__init__(self, arg1)
You write:
Python
super().__init__(arg1)
It’s cleaner, safer, and future-proof.
🔁 Real Example: Inheriting from a Parent Class
Python
class Animal:
def __init__(self, name):
self.name = name
def speak(self):
print(f"{self.name} makes a sound.")
Now a child class:
Python
class Dog(Animal):
def __init__(self, name, breed):
super().__init__(name) # Reuse Animal's __init__
self.breed = breed
def speak(self):
super().speak() # Call parent method
print(f"{self.name} barks!")
Python
d = Dog("Bruno", "Labrador")
d.speak()
Output:
Bruno makes a sound.
Bruno barks!
✅ Why Use super()
Instead of Hardcoding the Parent?
Reason | Benefit |
---|---|
Inheritance chains | Works even with multiple parents |
Code reuse | DRY: Don’t Repeat Yourself |
Less error-prone | No need to remember parent name |
Future-proof | Safe if you rename parent class |
🎯 When to Use super()
- In the child class’s
__init__()
to reuse the parent’s setup logic - To call parent methods you’re overriding but still want to use
- Inside mixins or multi-level inheritance chains
⚠️ Common Mistakes
❌ Mistake 1: Forgetting parentheses
Python
super.__init__(name) # ❌
✅ Fix:
Python
super().__init__(name)
❌ Mistake 2: Not calling super().__init__()
in child class
If you skip it, parent setup doesn’t happen causing bugs later.
💡 Real-World Analogy
Think of
super()
like borrowing your parent’s tools while building your own version you extend their logic rather than reinvent it.
🧪 Bonus: Works with super().method()
It’s not just for __init__
. You can call any method:
Python
class A:
def say_hello(self):
print("Hello from A")
class B(A):
def say_hello(self):
super().say_hello()
print("Hello from B")