我正在为 OOP 类(class)测试一些代码,但我遇到了问题。我正在编写一个圆和一个圆柱,圆类也在圆柱的初始化中。我有 2 个圆柱体参数,但是当我给出 2 个参数时,据说我只需要 1 个,如果我给出一个参数而不是它给出的输出,则缺少一个。
变量 a 可以工作,但错误在变量 b 中。我做错了什么
import math
class CCircle:
def __init__(self):
self._radius = 0
@property
def area(self):
return self._radius**2 * math.pi
@area.setter
def area(self, value):
self._radius = math.sqrt(value / math.pi)
@property
def circumference(self):
return self._radius * 2 * math.pi
@circumference.setter
def circumference(self, value):
self._radius = value / (2 * math.pi)
class CCylinder:
def __init__(self, radius, height):
self._circle = CCircle(radius)
self._height = height
@property
def circumference(self):
return self._circle.circumference
@property
def ground_area(self):
return self._circle.area
@property
def total_area(self):
return self._circle.area + self._height * self._circle.circumference
@property
def volume(self):
return self._circle.area * self._height
a = CCircle()
b = CCylinder(1,4)
init() takes 1 positional argument but 2 were given
最佳答案
你的 CCircle 类应该像这样开始
class CCircle:
def __init__(self, radius=0):
self._radius = radius
这样您就可以获得您似乎想要的默认半径 0,但也可以像在 CCylinder 类的初始化代码中那样使用半径值对其进行初始化。
关于python - __init__() 采用 1 个位置参数,但给出了 2 个,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58175886/