import math
class Cylinder:
def __init__(self):
self.r = r ; self.h =h
def GetVolume(self):
return math.pi*r**2*h
#请在此处写出Cylinder类定义的代码(提示:计算体积时使用math.pi作为圆周率)
if __name__=='__main__':
r=eval(input('半径:')) #输入半径
h=eval(input('高:')) #输入高
c=Cylinder() #创建Cylinder对象
print('radius:%.2f,height:%.2f'%(c.r,c.h)) #输出半径和高
print('volume:%.2f'%c.GetVolume()) #输出体积
构造函数中的参数是不是要写这个和创建类对应的对象时是否输入参数有关,若创建对象的时候指定某个参数的值时,则在构造函数中就需要将这个参数输入进去。否则会报错说参数对应不一
本文介绍了一个简单的Python类——圆柱体(Cylinder),该类用于计算给定半径和高度的圆柱体体积。通过实例化类并输入半径与高度,程序能够输出圆柱体的体积。

被折叠的 条评论
为什么被折叠?



