Here’s me playing around with super() method:
class Rectangle:
def __init__(self, width, length):
self.width = width
self.length = length
def perimeter(self):
fvalue = (self.width * 2) + (self.length * 2)
return fvalue
def area(self):
fvalue = self.width * self.length
return fvalue
class Square(Rectangle):
def __init__(self, width, length):
super().__init__(width, length)
def perimeter(self):
return super().perimeter(self)
def area(self):
return super().area(self)
square = Square(width=3, length=3)
print(square.area())
now when if I run this code I will get an error that said
TypeError: area() takes 1 positional argument but 2 were given
which is weird because in Square.area() I’ve only passed 1 argument to the super.area() method.
I later removed that argument and the code works fine, but I’m still confused as of why this error had happened because in Square.__init__() I need to pass an argument for it to work. An explanation to this will be appreciated
>Solution :
You don’t need the methods in Square that duplicate the methods in the parent class. This will work fine:
class Rectangle:
def __init__(self, width, length):
self.width = width
self.length = length
def perimeter(self):
fvalue = (self.width * 2) + (self.length * 2)
return fvalue
def area(self):
fvalue = self.width * self.length
return fvalue
class Square(Rectangle):
def __init__(self, width, length):
super().__init__(width, length)
square = Square(width=3, length=3)
print(square.area())