Python super() Function
The super()
function is used to call a method from a parent class in a child class.
It allows you to access and call methods in the superclass that have been overridden in the subclass. This is particularly useful for avoiding code duplication and for ensuring that the correct method is called in the context of multiple inheritance.
Syntax
super()
super() Parameters
Python super()
function does not require parameters.
super() Return Value
Python super()
function returns an object that represents the parent class.
The super()
function in Python returns a proxy object, which is an intermediary object that can invoke methods from the superclass. This mechanism is known as indirection, as it allows for the referencing of the superclass through super()
, enabling flexibility in calling superclass methods. The indirection is determined at runtime, making it possible to dynamically switch between different superclasses as needed.
Examples
Example 1: super() with Single Inheritance
In the case of single inheritance, we use super()
to refer to the base class.
For example, create Animal
class and the Dog
class that inherits Animal
:
class Animal:
def __init__(self, name):
self.name = name
class Dog(Animal):
def __init__(self, name, breed):
super().__init__(name) # Calling the __init__ method of Animal
self.breed = breed
d = Dog("Buddy", "Golden Retriever")
print(d.name) # Output: Buddy
print(d.breed) # Output: Golden Retriever
output
Buddy
Golde Retriever
Observe that we called the __init__()
method of Animal
Class from the Dog class in this way: super().__init__('Dog')
.
Example 2: super() with Multiple Inheritance
class Animal:
def __init__(self, Animal):
print(Animal, 'is an animal.');
class Mammal(Animal):
def __init__(self, mammalName):
print(mammalName, 'is a warm-blooded animal.')
super().__init__(mammalName)
class NonWingedMammal(Mammal):
def __init__(self, NonWingedMammal):
print(NonWingedMammal, "can't fly.")
super().__init__(NonWingedMammal)
class NonMarineMammal(Mammal):
def __init__(self, NonMarineMammal):
print(NonMarineMammal, "can't swim.")
super().__init__(NonMarineMammal)
class Dog(NonMarineMammal, NonWingedMammal):
def __init__(self):
print('Dog has 4 legs.');
super().__init__('Dog')
d = Dog()
print('')
bat = NonMarineMammal('Bat')
output
Dog has 4 legs.
Dog can't swim.
Dog can't fly.
Dog is a warm-blooded animal.
Dog is an animal.
Bat can't swim.
Bat is a warm-blooded animal.
Bat is an animal.
Example 3: Using super() in a Method
This example demonstrates how super()
can be used within a method to call a method from the superclass.
class Parent:
def print_message(self):
print("Hello from Parent")
class Child(Parent):
def print_message(self):
super().print_message() # Calling the print_message method of Parent
print("Hello from Child")
c = Child()
c.print_message()
output
Hello from Parent
Hello from Child
Example 4: Using super() in a List Comprehension
Using super()
in list comprehensions can be tricky due to the scope of self
. A workaround is to call super()
outside the list comprehension and then use it inside.
In this example, s = super()
is used outside the list comprehension to ensure that super()
is called in the correct scope. Then, s.print_message()
is used inside the list comprehension to call the method from the parent class:
class Parent:
def print_message(self):
print("Hello from Parent")
class Child(Parent):
def print_messages(self):
s = super()
return [s.print_message() for _ in range(3)]
c = Child()
c.print_messages()
output
Hello from Parent
Hello from Parent
Hello from Parent
Another example to understand better:
- Suppose you have a class hierarchy where a subclass needs to customize the behavior of a method from its parent class, but also wants to include the parent class's method behavior in its own. This can be achieved by using
super()
within a list comprehension to call the parent class's method.
In this example:
- The
Animal
class has amake_sound
method that returns a simple sound description. - The
Dog
class inherits fromAnimal
and overrides themake_sound
method to include its own sounds. - Within the
make_sound
method of theDog
class,super().make_sound()
is used within a list comprehension to call the parent class's make_sound method. This returns a list containing the parent class's sound description, which is then extended with additional dog-specific sounds. - The list comprehension is used here to conveniently construct a list of sound descriptions, showcasing the flexibility of
super()
in customizing subclass behavior while still leveraging the parent class's methods.
class Animal:
def __init__(self, name):
self.name = name
def make_sound(self):
return f"{self.name} makes a sound."
class Dog(Animal):
def make_sound(self):
sounds = [super().make_sound()]
sounds.extend([f"{self.name} barks.", f"{self.name} howls."])
return sounds
# Create an instance of Dog
my_dog = Dog("Rex")
# Use list comprehension to call make_sound and print each sound
for sound in my_dog.make_sound():
print(sound)
output
Rex makes a sound.
Rex barks.
Rex howls.