Jessy White
Jessy White

Reputation: 297

Using the super() method in python

I have to create a Square class derived from the Rectangle class using the super() method. I've been using it for other methods and when I use it in a derived method I only put

super().__init__()

but when I use it for the square method I get an error

TypeError: __init__() missing 4 required positional arguments: 'x', 'y', 'width', and 'height'

Where would I put the 4 arguments if for a square I already put in its own initialization that it requires only 3?

I don't know if it is important but Rectangle class is derived from another class Polygon, maybe there is something I am missing? Here's the code:

class Rectangle(Polygon):
    def __init__(self, x, y, width, height):
        super().__init__()
        self.add_point( (x, y) )
        self.add_point( (x + width, y) )
        self.add_point( (x + width, y + height) )
        self.add_point( (x, y + height) )


class Square(Rectangle):
    def __init__(self,x,y,length, width):
        super().__init__()
        self.add_point( (x,y))
        self.add_point( (x+length, y))
        self.add_point( (x+length, y+ length))
        self.add_point( (x, y+length))

Upvotes: 1

Views: 289

Answers (1)

Jacob Valenta
Jacob Valenta

Reputation: 6769

When you are calling super().__init__() be sure to pass the appropriate arguments to it.

super().__init__(x, y, width, height)

To explain: In the context of Square, calling super().__init__() is calling Rectangle.__init__ since it is the subclass. Then Rectangle's __init__ calls super.__init__() which is calling Polygon.__init__(). All of these calls need to have the correct arguments for the init funciton they are calling.

Upvotes: 2

Related Questions