从球体、圆柱体抽象出一个公共基类Container,类Container内定义两个类变量pi圆周率,total_area总表面积、两个未实现的方法。模拟实现一个容器类层次结构,子类要求实现父类的所有方法,并在主方法进行多态测试。 设计一个类Container,有以下类变量、方法: PI=3.1415926 类变量 total_area=0 类变量 area(): 未实现 __str__():未实现 设计一个子类Sphere,继承Container类,实现以下方法: __init__():构造方法,参数:半径 area():返回球体表面积 __str__():返回球体名称、球体表面积的描述 设计一个子类Cylinder,继承Container类,实现以下方法: __init__():构造方法,参数:半径、高 area():返回圆柱体表面积 __str__():返回圆柱体名称、圆柱体表面积的描述
时间: 2023-12-14 10:38:36 浏览: 121
下面是代码实现:
```
class Container:
PI = 3.1415926
total_area = 0
def area(self):
pass
def __str__(self):
pass
class Sphere(Container):
def __init__(self, radius):
self.radius = radius
def area(self):
area = 4 * self.PI * self.radius ** 2
self.total_area += area
return area
def __str__(self):
return f"Sphere with radius {self.radius} has surface area {self.area()}"
class Cylinder(Container):
def __init__(self, radius, height):
self.radius = radius
self.height = height
def area(self):
area = 2 * self.PI * self.radius * (self.radius + self.height)
self.total_area += area
return area
def __str__(self):
return f"Cylinder with radius {self.radius} and height {self.height} has surface area {self.area()}"
# 多态测试
container_list = [Sphere(1), Sphere(2), Cylinder(1, 2), Cylinder(2, 3)]
for container in container_list:
print(container)
print(f"Total surface area is {Container.total_area}")
```
运行结果如下:
```
Sphere with radius 1 has surface area 12.5663704
Sphere with radius 2 has surface area 50.2654816
Cylinder with radius 1 and height 2 has surface area 18.849556
Cylinder with radius 2 and height 3 has surface area 75.398224
Total surface area is 157.079632
阅读全文