What is super() Function in Python: Simple Explanation and Example
super() function in Python is used to call a method from a parent class inside a child class. It helps you reuse code from the parent class without explicitly naming it, making your code cleaner and easier to maintain.How It Works
Imagine you have a family recipe book, and you want to add your own twist to a recipe without rewriting the whole thing. The super() function works like referring back to the original recipe before adding your changes.
In Python, when you create a child class that inherits from a parent class, you might want to use some of the parent's methods but also add or change some parts. Using super() lets you call the parent’s method directly, so you don’t have to rewrite the same code again.
This makes your code easier to manage and avoids mistakes because you rely on the tested parent class methods while extending or customizing behavior in the child class.
Example
This example shows a parent class Animal with a method sound(). The child class Dog uses super() to call the parent method and then adds its own message.
class Animal: def sound(self): print("Animal makes a sound") class Dog(Animal): def sound(self): super().sound() # Call the parent class method print("Dog barks") my_dog = Dog() my_dog.sound()
When to Use
Use super() when you want to extend or customize behavior from a parent class without rewriting its code. It is especially useful in complex class hierarchies where multiple classes inherit from each other.
For example, in a program modeling vehicles, you might have a base class Vehicle with common features, and child classes like Car or Bike that add specific features. Using super() helps you keep shared code in one place and add only what’s unique in each child.
Key Points
super()calls methods from a parent class.- It helps avoid repeating code in child classes.
- Works well with multiple inheritance to manage method resolution order.
- Improves code readability and maintainability.
Key Takeaways
super() lets child classes use parent class methods easily.