我正在撰寫一個程式來使用繼承來查找圓柱體的體積。但是,我收到以下錯誤,我不確定如何解決它:
TypeError: __init__() missing 1 required positional argument: 'height'
這是我的代碼:
class Circle:
def __init__(self,radius,height):
self.radius = radius
self.height = height
class Cylinder(Circle):
def __init__(self,radius,height):
super().__init__(radius, height)
self.volume = 3.14 * (self.radius ** 2) * self.height
def set_volume(self):
print(self.volume)
radius = float(input("radius:"))
height = float(input("height:"))
cyl = Cylinder(radius,height)
print("Cylinder volume:", cyl.set.volume())
uj5u.com熱心網友回復:
您__init__對超類的呼叫不正確。您需要顯式傳入半徑和高度引數,而不是傳入超類的名稱。
super().__init__(Circle)
應該
super().__init__(radius, height)
uj5u.com熱心網友回復:
我建議你學習一點 OOP 和類之間的關系,因為這里不是繼承,與輸出錯誤無關。
首先,圓柱體形狀是一種 3d 幾何形式,可以聚合一個圓或實作另一個與圓的介面,但它是獨立的。
所以這種形式不是一個家庭,不應該有繼承的聯系。
有關軟體開發中聚合和組合的更多有趣資訊,請參閱此參考資料。
我為你實作了一個功能代碼,只是一個重構。
class Circle:
def __init__(self, radius):
self._radius = radius
self._area = 3.14 * (self._radius ** 2)
@property
def radius(self):
return self._radius
@property
def area(self):
return self._area
class Cylinder:
def __init__(self, radius, height, circle = None):
self._height = height
self._circle = circle if circle else Circle(radius)
self._volume = self._circle.area * self._height
@property
def heigth(self):
return self._height
@property
def volume(self):
return self._volume
@property
def area(self):
return self._circle.area
# radius = float(input("radius:"))
# height = float(input("height:"))
radius = 5
height = 10
circle = Circle(radius)
cylinder = Cylinder(radius, height, circle = circle)
print("circle area:", circle.radius)
print("Cylinder area:", cylinder.area)
print("Cylinder height:", cylinder.heigth)
print("Cylinder volume:", cylinder.volume)
uj5u.com熱心網友回復:
由于高度是與圓柱體相關的屬性,我們將把height屬性放在Cylinder類中,而基類Circle將只有radius屬性。
你最好做的如下
class Circle:
def __init__(self, radius):
self.radius = radius
class Cylinder(Circle):
def __init__(self, radius, height):
super().__init__(radius)
self.height = height # It makes sense to put height in the cyclinder here
self.volume = 3.14 * (self.radius ** 2) * self.height
def set_volume(self):
print(self.volume)
radius = float(input("radius:"))
height = float(input("height:"))
cyl = Cylinder(radius, height)
print("Cylinder volume:", cyl.set_volume())
uj5u.com熱心網友回復:
#我指的是正確的代碼
class Circle:
def __init__(self, radius):
self.radius = radius
class Cylinder(Circle):
def __init__(self, radius, height):
super().__init__(radius)
self.height = height
self.volume = 3.14 * (self.radius ** 2) * self.height
def set_volume(self):
print("Cylinder volume:",self.volume)
radius = float(input("radius:"))
height = float(input("height:"))
cyl = Cylinder(radius, height)
cyl.set_volume()
轉載請註明出處,本文鏈接:https://www.uj5u.com/net/446025.html
上一篇:如何獲取類中變數的所有值?
下一篇:為類函式中的引數設定條件
