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()
You can initialise the Square class much more briefly by relying on the already existing class Rectangle
# Create a Square class that will inherit from the Rectangle class class Square(Rectangle): def __init__(self, length): super().__init__(length, length)
In this example super() was used without explicitly specifying arguments. By default two arguments are passed - the name of the class and self.
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 # Create a Square class that will inherit from the Rectangle class class Square(Rectangle): def __init__(self, length): super(Square, self).__init__(length, length) square = Square(4) print(square.area()) rectangle = Rectangle(2,4) print(rectangle.area())
Article author: Andrei Olegovich