简体   繁体   中英

How do I only inherit some variables from a super class in Python

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')

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.

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)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM