定义父类Shape,该类包含计算面积的方法area,通过继承实现父类的方法,分别计算不同图形(圆、三角形、矩形)的面积。
时间: 2024-03-01 21:52:52 浏览: 44
好的,以下是示例代码:
```python
class Shape:
def area(self):
pass
class Circle(Shape):
def __init__(self, radius):
self.radius = radius
def area(self):
return 3.14 * self.radius ** 2
class Triangle(Shape):
def __init__(self, base, height):
self.base = base
self.height = height
def area(self):
return 0.5 * self.base * self.height
class Rectangle(Shape):
def __init__(self, width, height):
self.width = width
self.height = height
def area(self):
return self.width * self.height
```
以上代码中,我们定义了一个父类`Shape`,包含了一个抽象方法`area`。接着我们定义了三个子类`Circle`、`Triangle`、`Rectangle`,它们分别继承了`Shape`类,并实现了`area`方法来计算不同形状的面积。`Circle`类使用圆的半径计算面积,`Triangle`类使用底边和高计算面积,`Rectangle`类使用宽和高计算面积。
这里采用了面向对象编程的思想,通过继承实现代码的重用和扩展。这样,当我们需要计算其他形状的面积时,只需要定义一个新的子类,并实现`area`方法即可。