__ init __()接受1个位置参数,但给出2个位置参数

问题描述 投票:1回答:2

我正在为课程OOP测试一些代码,但是遇到了问题。我正在编写一个圆和一个圆柱,圆的类也位于圆柱的初始化中。我对圆柱有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个]

python python-3.x class inner-classes
2个回答
2
投票

问题在于此行:

self._circle = CCircle(radius)

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


1
投票

您应该像这样开始您的CCircle课程

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

以便获得您似乎想要的默认半径0,但也可以像在CCylinder类的init代码中一样使用半径值对其进行初始化。

© www.soinside.com 2019 - 2024. All rights reserved.