声明抽象基类Shape,由它派生出5个派生类;Circle(圆形)、Square(正方形)、Rectangle(矩形)、Trapezoid(梯形)、Triangle(三角形),分别计算几种图形的面积,并求它们的和并显示出来。
时间: 2023-07-10 15:31:16 浏览: 90
好的,这是一个关于面积计算的问题,我可以为您提供一个Python的实现代码,如下所示:
```python
from abc import ABC, abstractmethod
class Shape(ABC):
@abstractmethod
def area(self):
pass
class Circle(Shape):
def __init__(self, r):
self.r = r
def area(self):
return 3.14 * self.r * self.r
class Square(Shape):
def __init__(self, a):
self.a = a
def area(self):
return self.a * self.a
class Rectangle(Shape):
def __init__(self, a, b):
self.a = a
self.b = b
def area(self):
return self.a * self.b
class Trapezoid(Shape):
def __init__(self, a, b, h):
self.a = a
self.b = b
self.h = h
def area(self):
return (self.a + self.b) * self.h / 2
class Triangle(Shape):
def __init__(self, a, h):
self.a = a
self.h = h
def area(self):
return self.a * self.h / 2
# 计算各种图形的面积
circle = Circle(3)
square = Square(4)
rectangle = Rectangle(3, 5)
trapezoid = Trapezoid(2, 4, 3)
triangle = Triangle(4, 3)
# 计算它们的和
total_area = circle.area() + square.area() + rectangle.area() + trapezoid.area() + triangle.area()
# 显示结果
print("圆形面积为:", circle.area())
print("正方形面积为:", square.area())
print("矩形面积为:", rectangle.area())
print("梯形面积为:", trapezoid.area())
print("三角形面积为:", triangle.area())
print("总面积为:", total_area)
```
运行代码后,控制台上会输出各种图形的面积以及它们的总面积。希望这个代码可以帮到您!
阅读全文