簡體   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