builtins.TypeError:__ init __()缺少2个必需的位置参数:' height'和' radius'

时间:2017-03-29 20:13:20

标签: python

我收到的错误是说我错过了2个必要的位置参数:' height'和' radius。'我觉得我已经尝试了一切,但我知道我错过了一些小事。有帮助吗? 谢谢

# import math
import math

class SodaCan :
    # Constructs sodaCan with a given height and radius
    # @param height = given height and radius = given radius
    def __init__(self, height, radius):
        self._height = height
        self._radius = radius

    # Constructs the volume with the given height and radius
    def volume(self):
        self._volume = (pi * (self._radius ** 2) * self._height)

    # Constructs the Surface Area with the given height and radius
    def surfaceArea(self):
        self._surfaceArea = (2 * pi * self._radius * self._height) + (2 * pi   * (self._radius)**2)

    # Return the volume
    def getVolume(self):
        return self._volume

    # Return the Surface Area
    def getSurfaceArea(self):
        return self._surfaceArea

我不确定我在这里做错了什么。下面是我的代码的测试程序。

## 
# This program test the sodaCan.py
##

# import math so the program can read pi
import math

# from the file folder, ipmort the code from program 'sodaCan'
from sodaCan import SodaCan

mySodaCan = SodaCan()
mySodaCan.height(10)
mySodaCan.radius(4)

print(mySodaCan.getVolume())
print(mySodaCan.getSurfaceArea())

2 个答案:

答案 0 :(得分:2)

当您像这样定义初始化程序时:

class SodaCan:

    def __init__(self, height, radius):
        ...

您说高度和半径必需。必须指定它们才能创建汽水罐实例。

mySodaCan = SodaCan(height=10, radius=4)

如果希望它们是可选的,则可以在定义__init__方法时为这些参数指定默认值。然后,在创建实例时,如果在创建实例时省略,则参数将采用默认值。

答案 1 :(得分:2)

初始化类时,需要传递高度和半径。 init类中的参数意味着在初始化类时必须传递它们。像这样的东西会起作用:

height = 40
radius = 10
a = SodaCan(height, radius)