super().__init__()
Thu Feb 22 2024 15:18:13 GMT+0000 (Coordinated Universal Time)
Saved by
@aguest
#python
#classes
class Rectangle:
def __init__(self, length, width):
self.length = length
self.width = width
def area(self):
return self.length * self.width
class Square(Rectangle):
def __init__(self, length):
# Call the __init__ method of the parent class (Rectangle)
# super() refers to the parent class of this class
# Actually using the __init__ method of `Rectangle` here
# which needs 2 parameters, `length` and `width`. Since
# a square is length==width then we use `length` twice.
super().__init__(length, length)
my_square = Square(5)
my_square.area() # 25
content_copyCOPY
`super().__init__` calls the parent class' `__init__` method.
This allows you to reuse the parent's `__init__` method while customizing the child's `__init__` method at the same time.
In the example above, *Rectangle* takes 2 parameters (`length` and `width`), but for a square it's length is equal to it's width so we only need 1 parameter (`length`). We customize the *Square* class' `__init__` method to only require 1 parameter and then call the `__init__` method of *Rectangle* by using `length` for both `length` and `width`.
Comments