python 3设计一个获取面积的GetArea函数方法,要求能支持三角形矩形梯形的面面积
时间: 2024-10-19 22:04:13 浏览: 64
接口实现面积与周长运算
在Python中,设计一个通用的`GetArea`函数来计算不同形状(三角形、矩形和梯形)的面积,我们可以创建一个基础的抽象基类(如Shape),然后为每个具体的形状(Triangle、Rectangle、Trapezoid)定义子类,并在这些子类中实现各自的`__init__`方法初始化边长或属性以及`GetArea`方法。这里是一个简单的示例:
```python
class Shape:
def __init__(self):
pass
def GetArea(self):
raise NotImplementedError("Subclasses should implement this method.")
class Triangle(Shape):
def __init__(self, base, height):
self.base = base
self.height = height
def GetArea(self):
return 0.5 * self.base * self.height
class Rectangle(Shape):
def __init__(self, width, length):
self.width = width
self.length = length
def GetArea(self):
return self.width * self.length
class Trapezoid(Shape):
def __init__(self, a, b, height):
self.a = a # 第一条底边
self.b = b # 第二条底边
self.height = height
def GetArea(self):
return (self.a + self.b) / 2 * self.height
def get_area(shape_type, *args):
if shape_type == "triangle":
area = Triangle(*args).GetArea()
elif shape_type == "rectangle":
area = Rectangle(*args).GetArea()
elif shape_type == "trapezoid":
area = Trapezoid(*args).GetArea()
else:
raise ValueError(f"Unsupported shape type: {shape_type}")
return area
# 使用示例
triangle_area = get_area("triangle", 4, 6)
print(f"三角形面积: {triangle_area}")
rectangle_area = get_area("rectangle", 5, 8)
print(f"矩形面积: {rectangle_area}")
trapezoid_area = get_area("trapezoid", 7, 9, 5)
print(f"梯形面积: {trapezoid_area}")
```
阅读全文