Understanding the super() function in Python
In Python, the super()
function is used to refer to the parent class of a subclass. It allows you to access methods and properties of the parent class, and can be especially useful when you want to override a method defined in the parent class.
Here is the basic syntax for using the super()
function in Python:
class SubClass(SuperClass):
def method(self):
super().method()
Now, let’s look at en example:
class Rectangle:
def __init__(self, width, height):
self.width = width
self.height = height
def area(self):
return self.width * self.height
def perimeter(self):
return 2 * (self.width + self.height)
class Square(Rectangle):
def __init__(self, side_length):
super().__init__(side_length, side_length)
square_obj = Square(5)
print('area:', square_obj.area()) # area: 25
print('perimeter:', square_obj.perimeter()) # perimeter: 20
In this example, the Square
class is a subclass of the Rectangle
class. The Square
class has its own __init__
method, but it also wants to make use of the __init__
method of the Rectangle
class to set the width
and height
attributes. To do this, it calls super().__init__(side_length, side_length)
, which calls the __init__
method of the Rectangle
class and passes it the side_length
argument twice (since a square has equal sides).
If you find this tutorial helpful or would like to reach out, feel free to get in touch with me on here, Github or Linkedin. Happy coding!