super()
Introduction
Example of creating similar classes without super()
class Rectangle:
def __init__(self, length, width):
self.length = length
self.width = width
def area(self):
return self.length * self.width
def perimeter(self):
return 2 * self.length + 2 * self.width
class Square:
def __init__(self, length):
self.length = length
def area(self):
return self.length * self.length
def perimeter(self):
return 4 * self.length
square = Square(4)
print(square.area())
rectangle = Rectangle(2,4)
print(rectangle.area())
16 8
Example of using super()
It is much shorter to initialize the Square class by building on the existing class Rectangle
# Let us create a Square class that inherits from the Rectangle class
class Square(Rectangle):
def __init__(self, length):
super().__init__(length, length)
Article author: Andrei Olegovich