在shape 类基础上设计圆形、矩形、三角形:梯形四个子类,要求根据实际形状重写getArea方法
时间: 2023-12-28 20:04:44 浏览: 140
可以定义一个基类 `Shape`,包括 `getArea()` 方法,然后定义四个子类 `Circle`(圆形)、`Rectangle`(矩形)、`Triangle`(三角形)和 `Trapezoid`(梯形),并对每个子类重写 `getArea()` 方法。
以下是一个示例代码:
```python
import math
class Shape:
def getArea(self):
pass
class Circle(Shape):
def __init__(self, radius):
self.radius = radius
def getArea(self):
return math.pi * self.radius ** 2
class Rectangle(Shape):
def __init__(self, width, height):
self.width = width
self.height = height
def getArea(self):
return self.width * self.height
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 Trapezoid(Shape):
def __init__(self, a, b, height):
self.a = a
self.b = b
self.height = height
def getArea(self):
return 0.5 * (self.a + self.b) * self.height
```
使用示例:
```python
c = Circle(5)
print(c.getArea()) # 输出 78.53981633974483
r = Rectangle(3, 4)
print(r.getArea()) # 输出 12
t = Triangle(2, 6)
print(t.getArea()) # 输出 6.0
tr = Trapezoid(2, 4, 3)
print(tr.getArea()) # 输出 9.0
```
阅读全文