The super()
function in Python is used to call methods from a parent class inside a child class.
It’s commonly used in inheritance to extend or customize the behavior of parent class methods.
Example 1: Calling a Parent Method
class Animal:
def speak(self):
print("Animal speaks")
class Dog(Animal):
def speak(self):
super().speak() # Calls the speak method from Animal
print("Dog barks")
# Create an object of Dog
dog = Dog()
dog.speak()
Output:
Animal speaks
Dog barks
Here, the Dog
class overrides the speak()
method but still uses super()
to call the parent class’s version.
Example 2: Using super() in Constructors
class Person:
def __init__(self, name):
self.name = name
class Student(Person):
def __init__(self, name, student_id):
super().__init__(name) # Calls Person.__init__()
self.student_id = student_id
student = Student("Alice", "S123")
print(student.name, student.student_id)
Output:
Alice S123
Here, super().__init__(name)
ensures that the Person class initializes the name attribute, while Student adds its own attribute.
Why Use super()?
- Avoids hardcoding parent class names → More flexible if class hierarchy changes.
- Supports multiple inheritance → Works with Python’s Method Resolution Order (MRO).
- Cleaner and maintainable code → Keeps constructors and overridden methods simpler.
Best Practices
- Always use
super()
instead of directly callingParentClass.method()
. - Use it in constructors (
__init__
) when extending parent initialization. - Remember: In multiple inheritance,
super()
follows the MRO sequence.
👉 Next tutorial: Python Magic/Dunder Methods