请用接口实现以下UML图 测试类中,有三个柱体,分别以三角形,圆形,矩形为底面积,求它们的体积。 测试用例::三角形边:(3,4,5);圆形半径:2; 矩形边(3,4),柱体高:6.
时间: 2024-06-13 19:08:41 浏览: 176
```python
# 定义抽象类Geometry
from abc import ABC, abstractmethod
class Geometry(ABC):
@abstractmethod
def getArea(self):
pass
# 定义Circle类,继承Geometry类
class Circle(Geometry):
def __init__(self, r):
self.r = r
def getArea(self):
return 3.14 * self.r * self.r
# 定义Triangle类,继承Geometry类
class Triangle(Geometry):
def __init__(self, a, b, c):
self.a = a
self.b = b
self.c = c
def getArea(self):
p = (self.a + self.b + self.c) / 2
return (p * (p - self.a) * (p - self.b) * (p - self.c)) ** 0.5
# 定义Rectangle类,继承Geometry类
class Rectangle(Geometry):
def __init__(self, l, w):
self.l = l
self.w = w
def getArea(self):
return self.l * self.w
# 定义Cylinder类
class Cylinder:
def __init__(self, bottom, h):
self.bottom = bottom
self.h = h
def getVolume(self):
return self.bottom.getArea() * self.h
# 创建三个底面不同的几何图形
circle = Circle(2)
triangle = Triangle(3, 4, 5)
rectangle = Rectangle(3, 4)
# 创建三个柱体
cylinder1 = Cylinder(circle, 6)
cylinder2 = Cylinder(triangle, 6)
cylinder3 = Cylinder(rectangle, 6)
# 计算三个柱体的体积
print("圆柱体积为:", cylinder1.getVolume())
print("三角柱体积为:", cylinder2.getVolume())
print("矩形柱体积为:", cylinder3.getVolume())
```
--相关问题--:
1. 什么是抽象类和抽象方法?
2. Python中如何
阅读全文