![](/img/trans.png)
[英]How do I properly inherit from a base class using Super() (Python 2/3)?
[英]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')
Square
是x
和y
相同的Shape
。 因此:
class Square(Shape):
def __init__(self, x):
super().__init__(x, x)
您只需要使用x
作為x
和y
參數調用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.