0

I am trying to make a subclass, Square, from a superclass, Shape.

class Shape :

     def __init__ (self, x, y) :
          self.x = x
          self.y = y
          self.description = "This shape has not been described yet"
      
     def area (self) :
          return self.x * self.y

     def describe (self, text) :
          self.description = text

I have tried

class Square (Shape) :

     def __init__ (self, x) :
          self.x = x
          self.y = x
          self.description = "This shape has not been described yet"

which seems to work, but the only thing that actually changes in Square is self.y = x, so I wonder if I could do the same thing without having to write self.x and self.description again.

(I tried doing something like this:

class Square (Shape) :

     def __init__ (self, x) :
          self.y = x
          super().__init__()

but, when I create a Square object, a type error occurs: TypeError: init() missing 2 required positional arguments: 'x' and 'y')

2 Answers 2

2

A Square is a Shape whose x and y are the same. Hence:

class Square(Shape):
    def __init__(self, x):
        super().__init__(x, x)

You just need to call Shape.__init__(self, x, y) with your x as both the x and y parameters.

Sign up to request clarification or add additional context in comments.

Comments

0

Just call the super function inside __init__. Put both the arguments equal to x.

class Square(Shape):
    def __init__(self, x):
        super().__init__(x, x)

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.