Python super()
The super()
function in Python is used to refer to the parent class. It returns a temporary object of the superclass, which allows you to call its methods.
The super()
function is often used in inheritance in order to call a method from the parent class, while also having the ability to add additional functionality to it in the child class.
Here's a basic example of how super()
can be used:
class ParentClass:
def __init__(self):
self.name = "Parent"
def display(self):
print("This is the Parent class")
class ChildClass(ParentClass):
def __init__(self):
super().__init__() # calling the parent class' __init__() method
self.name = "Child"
def display(self):
super().display() # calling the parent class' display() method
print("This is the Child class")
child = ChildClass()
child.display()
In this example, we create a parent class ParentClass
with a display()
method. We then create a child class ChildClass
that inherits from ParentClass
. In the child class, we use super().__init__()
to call the parent class' __init__()
method, which sets the name
attribute to "Parent". We also use super().display()
to call the parent class' display()
method and then print "This is the Child class".
When we create an instance of ChildClass
and call the display()
method, it first calls the parent class' display()
method, printing "This is the Parent class", and then continues to execute the lines of code in the child class' display()
method, printing "This is the Child class".