设计出一个求面积的Area类,要求能处理三角形、矩形、和圆形的面积计算,并能自动处理用户输入的异常
时间: 2025-07-05 09:01:50 浏览: 10
好的,我们可以设计一个名为`Area`的抽象基类,它包含一个通用的`calculateArea()`方法,然后为每个形状(三角形、矩形和圆形)创建具体的子类并实现这个方法。这里是一个简单的Python示例:
```python
from abc import ABC, abstractmethod
class Area(ABC):
@abstractmethod
def calculate_area(self, *args, **kwargs):
pass
class Triangle(Area):
def __init__(self, base, height):
self.base = base
self.height = height
def calculate_area(self):
try:
return 0.5 * self.base * self.height
except TypeError as e:
print(f"错误:{e}. 请输入正确的三角形边长和高度.")
class Rectangle(Area):
def __init__(self, length, width):
self.length = length
self.width = width
def calculate_area(self):
try:
return self.length * self.width
except TypeError as e:
print(f"错误:{e}. 请输入正确的矩形长度和宽度.")
class Circle(Area):
def __init__(self, radius):
self.radius = radius
def calculate_area(self):
try:
return 3.14159 * (self.radius ** 2)
except TypeError as e:
print(f"错误:{e}. 请输入正确的圆的半径.")
def main():
shape_type = input("请选择形状(三角形、矩形、圆形):")
if shape_type == "三角形":
base = float(input("三角形底边长:"))
height = float(input("三角形高:"))
triangle = Triangle(base, height)
print(triangle.calculate_area())
elif shape_type == "矩形":
length = float(input("矩形长度:"))
width = float(input("矩形宽度:"))
rectangle = Rectangle(length, width)
print(rectangle.calculate_area())
elif shape_type == "圆形":
radius = float(input("圆的半径:"))
circle = Circle(radius)
print(circle.calculate_area())
else:
print("无效的选择,请从提供的选项中选择.")
if __name__ == "__main__":
main()
```
阅读全文
相关推荐


















