Python Basics: What is super()?

Sarang Surve
2 min readFeb 4, 2024

--

Hey There! Today, we’re diving into an essential Python topic called super() function. It’s a powerful tool that helps us work with inheritance in classes. Let’s get started on what exactly is a super() function.

What is super() function?

super() function is a built-in function in Python and it’s like a superhero when it comes to working with classes, it helps you call methods and access attributes from a parent or superclass within your subclass. Now, you might be wondering why I even need a super function.

Why use super() function?

Using super() function is essential when you want to extend the functionality of a parent class in your subclass, it keeps your code organized, maintains a clear hierarchy and prevents repetition.

How to use super() function?

Using super() function is super simple too. Suppose you have a parent class called animal and you want to create a subclass called dog.

In the dog subclass, you can use super() function like this.

# main.py
class Animal:
def speak(self):
print("Animal sound")

class Dog(Animal):
def speak(self):
super().speak() # Calls the 'speak()' method of the parent class
print("Woof!")

dog_instance = Dog()
dog_instance.speak()

If you create an instance of the dog class and call its speak method like this, it will first print animal sounds. The result of calling the parent class’s speak method followed by woof.

You can also pass arguments to the parent class’s methods using super, let’s say we want to pass the name of the animal. In this case, the __init__() method in the dog class overrides the __init__() method in the animal class to provide additional functionality while still making use of the parent class’s constructor.

# main.py
class Animal:
def __init__(self,name):
self.name = name

def speak(self):
print(self.name+" says ")

class Dog(Animal):
def __init__(self, name, emotion):
super().__init__(name) # Calls the parent class's constructor
self.emotion = emotion

def speak(self):
super().speak()
print("Woof "+self.emotion)

dog_instance = Dog("Whiskey", "happily")
dog_instance.speak()

Benefits

By using a super() function, you promote code reusability, which means writing less code and avoiding duplication. Plus it makes your code more maintainable as changes in the parent class automatically apply to the child class.

Conclusion

The super() function in Python is your best friend. When working with class inheritance, it allows you to inherit and extend behavior from parent classes, promoting code reusability and maintainability.

--

--

No responses yet