设计出一个求面积的Area类,要求能处理三角形,矩形和圆形的面积计算,并能自动处理用户输入的异常
时间: 2025-06-14 21:17:25 浏览: 18
为了创建一个能够处理不同类型形状(如三角形、矩形和圆形)并处理用户输入异常的Area类,我们可以设计一个通用的基类Shape,然后让具体的形状作为子类,每个子类都覆盖一个计算面积的方法。同时,我们还可以添加一个验证方法来检查用户提供的参数是否有效。以下是示例代码:
```python
import math
class Shape:
def __init__(self):
pass
def validate_input(self, *args):
raise NotImplementedError("Subclasses should implement this method")
def calculate_area(self):
raise NotImplementedError("Subclasses should implement this method")
class Triangle(Shape):
def __init__(self, base, height):
self.validate_input(base, height)
self.base = base
self.height = height
def validate_input(self, base, height):
if base <= 0 or height <= 0:
raise ValueError("Base and height must be positive numbers.")
def calculate_area(self):
return 0.5 * self.base * self.height
class Rectangle(Shape):
def __init__(self, width, height):
self.validate_input(width, height)
self.width = width
self.height = height
def validate_input(self, width, height):
if width <= 0 or height <= 0:
raise ValueError("Width and height must be positive numbers.")
def calculate_area(self):
return self.width * self.height
class Circle(Shape):
def __init__(self, radius):
self.validate_input(radius)
self.radius = radius
def validate_input(self, radius):
if radius <= 0:
raise ValueError("Radius must be a positive number.")
def calculate_area(self):
return math.pi * (self.radius ** 2)
# 示例用法
try:
shape_type = input("Enter 'triangle', 'rectangle', or 'circle': ")
if shape_type == 'triangle':
base, height = map(float, input("Enter triangle's base and height: ").split())
area = Triangle(base, height).calculate_area()
elif shape_type == 'rectangle':
width, height = map(float, input("Enter rectangle's width and height: ").split())
area = Rectangle(width, height).calculate_area()
elif shape_type == 'circle':
radius = float(input("Enter circle's radius: "))
area = Circle(radius).calculate_area()
else:
print("Invalid shape type.")
except ValueError as e:
print(f"Error: {str(e)}")
```
阅读全文
相关推荐


















