编写程序,定义一个抽象基类Shape,由它派生出3个派生类:Circle,Square,Rectangle,用一个函数printarea分别输出以上三者的面积,3个图形的数据在定义对象时给定。创建基类指针,指向各个派生类对象
时间: 2024-03-05 19:55:16 浏览: 94
好的,下面是代码示例:
```python
from abc import ABC, abstractmethod
class Shape(ABC):
@abstractmethod
def area(self):
pass
class Circle(Shape):
def __init__(self, radius):
self.radius = radius
def area(self):
return 3.14 * self.radius ** 2
class Square(Shape):
def __init__(self, side):
self.side = side
def area(self):
return self.side ** 2
class Rectangle(Shape):
def __init__(self, length, width):
self.length = length
self.width = width
def area(self):
return self.length * self.width
def printarea(shape):
print(f"The area is {shape.area()}")
circle = Circle(5)
square = Square(4)
rectangle = Rectangle(3, 6)
printarea(circle)
printarea(square)
printarea(rectangle)
shape_list = [Circle(2), Square(3), Rectangle(4, 5)]
for shape in shape_list:
printarea(shape)
```
运行结果如下:
```
The area is 78.5
The area is 16
The area is 18
The area is 12.56
The area is 9
The area is 20
```
阅读全文
相关推荐


















