Member-only story

The super() function in Python

Elshad Karimov
2 min readApr 9, 2024
Photo by Clément Hélardot on Unsplash

The super() function in Python is used to give access to methods and properties of a parent or sibling class. It allows you to call methods of the superclass in your subclass. The primary use case of super() is to extend the functionality of the inherited method.

Example: Using super() in Inheritance

Consider a base class Animal and a derived class Dog. We'll show how super() is used to call the constructor of the base class from the derived class.

class Animal:
def __init__(self, animal_name):
print("Animal constructor is called")
self.name = animal_name

def sound(self):
return "Animal makes a sound"

class Dog(Animal):
def __init__(self, name):
print("Dog constructor is called")
super().__init__(name) # Calling the constructor of the Animal class

def sound(self):
original_sound = super().sound() # Calling the sound method from the Animal class
return f"{original_sound} but a dog barks"

# Creating an instance of Dog
dog = Dog("Buddy")
print(dog.name) # Output: Buddy
print(dog.sound()) # Output: Animal makes a sound but a dog barks

In this example:

  • Animal is a base class with a constructor that initializes the name attribute and a method sound.

--

--

Elshad Karimov
Elshad Karimov

Written by Elshad Karimov

Software Engineer, Udemy Instructor and Book Author, Founder at AppMillers

No responses yet