我已經嘗試了一切,我的代碼似乎非常接近,但當我定義變量時,我不斷收到名稱錯誤。Python 3寫類返回表面積和球體積
from math import *
class Spheres:
def __init__(self, radius):
self.radius = r
self.area = 0
self.volume = 0
def getRadius(self):
return self.radius
def surfaceArea(self):
self.area = 4 * 3.14 * (r*r)
return (self.area)
def getVolume(self):
self.volume = (4/3) * 3.14 * (r * r * r)
return (self.volume)
def main():
r = input("Enter the radius of the sphere: ")
s = Spheres(r)
print("The volume of the sphere is: ", s.surfaceArea())
print("The surface area of the sphere is: ", s.volume())
if __name__ == '__main__':
main()
該錯誤消息我得到的是:
Traceback (most recent call last):
File "/local/files/jfult001/CSC221/lab10/9ball.py", line 30, in <module> main()
File "/local/files/jfult001/CSC221/lab10/9ball.py", line 26, in main print("The volume of the sphere is: ", s.surfaceArea())
File "/local/files/jfult001/CSC221/lab10/9ball.py", line 15, in surfaceArea self.area = 4 * 3.14 * (r*r)
NameError: global name 'r' is not defined
什麼是'NameError'?你能否把它列入你的問題? – 2013-04-22 06:59:14
另外,請檢查您的代碼縮進。上面的縮進是否準確地反映了你的實際代碼是如何縮進的? – 2013-04-22 07:00:36
不是類下的函數全都像第一個那樣縮進,錯誤是: – user2306249 2013-04-22 07:05:26