繁体   English   中英

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

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

我正在尝试从超类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

我努力了

class Square (Shape) :

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

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

(我试着做这样的事情:

class Square (Shape) :

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

但是,当我创建 Square object 时,出现类型错误:TypeError: init () missing 2 required positional arguments: 'x' and 'y')

Squarexy相同的Shape 因此:

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

您只需要使用x作为xy参数调用Shape.__init__(self, x, y)

只需在__init__中调用超级 function 即可。 将 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