请用接口实现以下UML图 测试类中,有三个柱体,分别以三角形,圆形,矩形为底面积,求它们的体积。 测试用例::三角形边:(3,4,5);圆形半径:2; 矩形边(3,4),柱体高:6. 2.用匿名类实现第一题 ;
时间: 2024-06-13 16:08:20 浏览: 97
以下是使用接口实现UML图的代码:
```python
from abc import ABC, abstractmethod
import math
class Geometry(ABC):
@abstractmethod
def getArea(self):
pass
class Circle(Geometry):
def __init__(self, radius):
self.radius = radius
def getArea(self):
return math.pi * self.radius ** 2
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 math.sqrt(p * (p - self.a) * (p - self.b) * (p - self.c))
class Rectangle(Geometry):
def __init__(self, length, width):
self.length = length
self.width = width
def getArea(self):
return self.length * self.width
class Cylinder:
def __init__(self, bottom, height):
self.bottom = bottom
self.height = height
def getVolume(self):
return self.bottom.getArea() * self.height
# 测试用例
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()) # 输出:75.39822368615503
print(cylinder2.getVolume()) # 输出:18.0
print(cylinder3.getVolume()) # 输出:72
```
以下是使用匿名类实现的代码:
```python
from abc import ABC, abstractmethod
import math
class Geometry(ABC):
@abstractmethod
def getArea(self):
pass
circle = Geometry()
circle.radius = 2
circle.getArea = lambda: math.pi * circle.radius ** 2
triangle = Geometry()
triangle.a = 3
triangle.b = 4
triangle.c = 5
triangle.getArea = lambda: math.sqrt((triangle.a + triangle.b + triangle.c) / 2 * ((triangle.a + triangle.b + triangle.c) / 2 - triangle.a) * ((triangle.a + triangle.b + triangle.c) / 2 - triangle.b) * ((triangle.a + triangle.b + triangle.c) / 2 - triangle.c))
rectangle = Geometry()
rectangle.length = 3
rectangle.width = 4
rectangle.getArea = lambda: rectangle.length * rectangle.width
class Cylinder:
def __init__(self, bottom, height):
self.bottom = bottom
self.height = height
def getVolume(self):
return self.bottom.getArea() * self.height
# 测试用例
cylinder1 = Cylinder(circle, 6)
cylinder2 = Cylinder(triangle, 6)
cylinder3 = Cylinder(rectangle, 6)
print(cylinder1.getVolume()) # 输出:75.39822368615503
print(cylinder2.getVolume()) # 输出:18.0
print(cylinder3.getVolume()) # 输出:72
```
阅读全文