任务是查找形状的面积和体积。设计代码时,请考虑以下形状:球形和圆柱体。 该类应该只有一个构造函数。另外,我们应该创建一个名为Shape的类 下面是我编写并返回输出的代码,但是如何使用新类进行形状转换并继承到测试中或其他方式。
import math
#class Shapes
class Test:
def __init__(self, *args):
self.radius = args[0]
if (len(args) == 2):
self.height = args[1]
self.area = 0
self.volume = 0
return super().__init__()
def Area(self,val):
radius = self.radius
if (val == "Sphere"):
area = 4 * 3.14 * radius ** 2
elif (val =="Cylinder"):
height = self.height
area = ((2 * 3.14 * radius) * (radius + height))
else:
area = 0
return area
def Volume(self,val):
radius = self.radius
if (val == "Sphere"):
volume = (4/3) * (3.14 * radius ** 2)
elif (val == "Cylinder"):
height = self.height
volume = 3.14 * radius * radius * height
else:
volume = 0
return volume
def main():
cylinder=Test(2,4)
print('Cylinder area:',cylinder.Area(enter code here'Cylinder'))
print('Cylinder volume:',cylinder.Volume('Cylinder'))
sphere=Test(3)
print('Sphere area:',sphere.Area('Sphere'))
print('Sphere volume:',sphere.Volume('Sphere'))
if __name__=='__main__':
main()
答案 0 :(得分:1)
在问题中指定:
class Shape
。 class Sphere
派生一个class Cylinder
和一个class Shape
。 然后,为了使用形状,
下面的示例可以做到这一点。
import math
class Shape:
"""abstract class for shapes"""
def __init__(self, radius):
self.radius = radius
def get_surface(self):
raise NotImplementedError
def get_volume(self):
raise NotImplementedError
class Sphere(Shape): # <-- inherits from Shape
def __init__(self, radius):
Shape.__init__(self, radius) # <-- can also use super().__init__(radius)
def get_surface(self):
return 4 * math.pi * self.radius**2 # <-- use math.pi constant i/o hard coding the value of pi
def get_volume(self):
return math.pi * self.radius**3 * 4/3
class Cylinder(Shape): # <-- inherits from Shape
def __init__(self, radius, height):
Shape.__init__(self, radius) # <-- can also use super().__init__(radius)
self.height = height
def get_surface(self):
return 2 * math.pi * self.radius * self.height + 2 * math.pi * self.radius**2
def get_volume(self):
return math.pi * self.radius**2 * self.height
def main():
cyl = Cylinder(2, 4)
print('Cylinder area:', cyl.get_surface()) # <-- call the methods on the object
print('Cylinder volume:', cyl.get_volume())
sph = Sphere(5)
print('Sphere area:',sph.get_surface())
print('Sphere volume:',sph.get_volume())
if __name__=='__main__':
main()
Cylinder area: 75.3982236862
Cylinder volume: 50.2654824574
Sphere area: 314.159265359
Sphere volume: 523.598775598