python - __init__() 采用 1 个位置参数,但给出了 2 个

标签 python python-3.x class inner-classes

我正在为 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/

相关文章:

不尊重 Python 修补模拟

python - 按时间间隔对列进行分箱并计算总和

Java,类类型列表

ruby - 如何在不计算重新分配的情况下计算类的实例?

python - Gunicorn - ValueError : '<path_to_sock.sock>' is not a socket

python - Networkx 在 Bokeh 中绘图 : how to set edge width based on graph edge weight

python - 似乎无法遍历键为数字字符串的已排序字典。您如何对字典进行排序以进行迭代?

Python 在数组 A 中找到元素,但在数组 B 中找不到

c++ - 运算符重载 c++ (x==y==z)

python - 在 Windows 上构建 Python C 扩展