【问题标题】:_init__() takes 1 positional argument but 2 were given__init__() 接受 1 个位置参数,但给出了 2 个
【发布时间】:2020-01-30 05:17:06
【问题描述】:

我正在测试 OOP 课程的一些代码,但遇到了问题。我正在编写一个圆和一个圆柱体,circle 类也在圆柱体的 init 中。我有 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() 接受 1 个位置参数,但给出了 2 个

【问题讨论】:

  • 问题在这里 -> self._circle = CCircle(radius)。您将radius 作为构造函数的参数传递,它不需要任何参数。

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


【解决方案1】:

问题出在这一行:

self._circle = CCircle(radius)

但是CCircle 类的__init__ 不接受任何参数(self 除外),所以这会导致错误。

【讨论】:

    【解决方案2】:

    你应该让你的 CCircle 类像这样开始

    class CCircle:
        def __init__(self, radius=0):
            self._radius = radius
    

    这样您就可以得到您想要的默认半径 0,但也可以使用半径值初始化它,就像您在 CCylinder 类的初始化代码中所做的那样。

    【讨论】:

      【解决方案3】:

      你可能在 .py 文件所在的地方有一个本地包文件夹,删除它应该可以解决你的问题

      【讨论】:

        猜你喜欢
        • 2017-04-22
        • 2017-11-23
        • 2022-01-04
        • 2019-10-27
        • 2018-05-06
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多