super() Built-in Function
Python - super()
Python super() builtin function is used to call a method in a parent class without explicitly naming the parent class. It is commonly used in object-oriented programming when defining a subclass that inherits from a superclass.
In this tutorial, you will learn the syntax of super() function, and then its usage with the help of example programs.
Syntax
The syntax of super()
function is
class super(type, object_or_type=None)
where
Parameter | Description |
---|---|
type | [Optional] An iterable like list, tuple, etc. |
object_or_type | [Optional] This determines the method resolution order to be searched. |
Examples
1. Call method in super class
In the following program, we defined two classes: Animal
and Dog
.
Dog
is a subclass of Animal
and inherits its __init__()
and speak()
methods. However, the Dog
class has its own __init__()
method that takes an additional argument breed
.
Python Program
class Animal:
def __init__(self, name):
self.name = name
def speak(self):
print(f"{self.name} makes a noise.")
class Dog(Animal):
def __init__(self, name, breed):
super().__init__(name)
self.breed = breed
def speak(self):
super().speak()
print(f"{self.name} barks.")
How are we using super() method here?
In the __init__()
method of the Dog
class, we call the __init__()
method of the Animal
class using super().__init__(name)
. This initializes the name
attribute of the Animal
class with the name
argument passed to the Dog
constructor.
In the speak()
method of the Dog
class, we call the speak()
method of the Animal
class using super().speak()
. This prints the message "Dog makes a noise." because self.name
is set to the value of name
passed to the Dog
constructor. Then, we print the message "Dog barks." to indicate that the Dog
class has its own behavior.
In the following program, we have created an instance mydog
of Dog
class, and called speak()
method on mydog
.
Python Program
class Animal:
def __init__(self, name):
self.name = name
def speak(self):
print(f"{self.name} makes a noise.")
class Dog(Animal):
def __init__(self, name, breed):
super().__init__(name)
self.breed = breed
def speak(self):
super().speak()
print(f"{self.name} barks.")
mydog = Dog('Jumpy', 'Bulldog')
mydog.speak()
Output
Jumpy makes a noise.
Jumpy barks.
Summary
In this Python Built-in Functions tutorial, we learned the syntax of super() built-in function, and how super()
allows you to call a method in a parent class without hard-coding the name of the parent class. This can make your code more flexible and easier to maintain, especially when dealing with complex class hierarchies.