简体   繁体   English

如何仅从 Python 中的超级 class 继承一些变量

[英]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.我正在尝试从超类Shape创建一个子类Square。

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.这似乎可行,但 Square 中唯一真正改变的是 self.y = x,所以我想知道是否可以在不必再次编写 self.x 和 self.description 的情况下做同样的事情。

(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')但是,当我创建 Square object 时,出现类型错误:TypeError: init () missing 2 required positional arguments: 'x' and 'y')

A Square is a Shape whose x and y are the same. Squarexy相同的Shape 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.您只需要使用x作为xy参数调用Shape.__init__(self, x, y)

Just call the super function inside __init__ .只需在__init__中调用超级 function 即可。 Put both the arguments equal to x .将 arguments 都设为x

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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