python3根据所学知识,设计Get Area函数,要求该函数能计算矩形, 三角形,圆形,梯形的面积
时间: 2024-10-24 19:17:22 浏览: 38
在Python中,你可以设计一个通用的`GetArea`函数,它接受形状的类型以及相应的属性作为输入参数,然后根据每个形状的特定公式来计算面积。这里是一个简单的示例:
```python
import math
class Shape:
def __init__(self, name, *args):
self.name = name
self.args = args
def get_area(self):
raise NotImplementedError("Subclass must implement this method")
class Rectangle(Shape):
def __init__(self, length, width):
super().__init__("Rectangle", length, width)
def get_area(self):
return self.args[0] * self.args[1]
class Triangle(Shape):
def __init__(self, base, height):
super().__init__("Triangle", base, height)
def get_area(self):
return 0.5 * self.args[0] * self.args[1]
class Circle(Shape):
def __init__(self, radius):
super().__init__("Circle", radius)
def get_area(self):
return math.pi * (self.args[0]**2)
class Trapezoid(Shape):
def __init__(self, a, b, height):
super().__init__("Trapezoid", a, b, height)
def get_area(self):
return 0.5 * (self.args[0] + self.args[1]) * self.args[2]
def GetArea(shape_type, *shape_params):
shapes = {
"Rectangle": Rectangle,
"Triangle": Triangle,
"Circle": Circle,
"Trapezoid": Trapezoid,
}
if shape_type in shapes:
return shapes[shape_type](*shape_params).get_area()
else:
print(f"Unsupported shape type: {shape_type}")
# 使用示例
area_rectangle = GetArea("Rectangle", 4, 6) # 面积为24
area_triangle = GetArea("Triangle", 3, 4) # 面积为6
area_circle = GetArea("Circle", 5) # 面积约为78.54
area_trapezoid = GetArea("Trapezoid", 3, 5, 4) # 面积为16
阅读全文