我正在使用python中的一个项目,我无法弄清楚为什么我在项目中收到错误。
该项目如下。
编写一个类来表示几何球体。您的课程应该实现以下方法:
__init__(self, radius)
创建一个具有给定半径的球体。getRadius(self)
返回此球体的半径surfaceArea(self)
返回球体的表面区域。 volume(self)
返回球体的体积。卷的公式是编写一个main()
方法,提示用户输入球体的半径,并告诉用户给定半径的表面积和体积是多少。
我目前的代码如下。
import math
class Spheres:
def __init__(self,radius):
self.radius = radius
self.area = 0
self.volumeResult = 0
def getRadius(self):
return self.radius
def surfaceArea(self):
r = self.radius
self.area = 4 * math.pi * (r * r)
return self.area
def volume(self):
r = self.radius
self.volumeResult = (4/3) * math.pi * (r * r * r)
return self.volumeResult
def main():
r = input("enter radius of circle:")
r = int(r)
radius = Spheres(r)
v = radius.volume()
a = radius.surfaceArea()
print ("volume of circle :" , v () )
print ("Surface Area of circle:" , a () )
main()
当我运行代码时,它看起来像这样
enter radius of circle:5 #### i enter 5 here to test it
Traceback (most recent call last):
File "C:\Users\Austin\Desktop\python bonus project\AustinBaker Python
bonus.py", line 30, in <module>
main()
File "C:\Users\Austin\Desktop\python bonus project\AustinBaker Python
bonus.py", line 27, in main
print ("volume of circle :" , v () )
TypeError: 'float' object is not callable
>>>
我不明白为什么代码根本不起作用。
答案 0 :(得分:0)
你的问题在这里:
print ("volume of circle :" , v () )
print ("Surface Area of circle:" , a () )
您正试图致电v
和a
,但这些变量无法调用float
s。
In [1]: v = 12.4
In [2]: callable(v)
Out[2]: False
In [3]: type(v)
Out[3]: float
仅print("volume of circle :" , v)
没有()
。
为了将来参考,追溯是您的朋友:
File "C:\Users\Austin\Desktop\python bonus project\AustinBaker Python
bonus.py", line 27, in main <--- ## the line number in your program where it all went wrong
print ("volume of circle :" , v () ) <-- ## the line of code that crapped out
TypeError: 'float' object is not callable <-- ## why it crapped out
翻译:
float
因此,如果v = 12.4
,您尝试将其称为函数:
print ("volume of circle :" , v () ) # ==> 12.4()
那是你的错误......
一些建议:
class Sphere:
def __init__(self,radius):
self._radius = radius
self._area = None
self._volume = None
@property
def area(self):
if self._area is None:
r = self.radius
self._area = 4 * math.pi * (r * r)
return self._area
@property
def volume(self):
if self._volume is None:
r = self.radius
self._volume = (4/3) * math.pi * (r * r * r)
return self._volume
@property
def radius(self):
return self._radius
@radius.setter
def radius(self, radius):
self._radius = radius
self._area = None
self._volume = None
所以这样:
In [1]: s = Sphere(2)
In [2]: s.area
Out[2]: 50.26548245743669
In [3]: s.volume
Out[3]: 33.510321638291124
In [4]: s.radius = 3
In [5]: s.volume
Out[5]: 113.09733552923254
In [6]: s.area
Out[6]: 113.09733552923255