写一个程序,定义抽象基类Shape,由它派生出3个派生类: Circle(圆形)、Rectangle(矩形)、Triangle(三角形),用一个函数printArea分别输出以上三者的面积,3个图形的数据在定义对象时给定。
时间: 2023-07-15 17:14:48 浏览: 91
下面是一个Python的实现示例:
```python
from abc import ABC, abstractmethod
import math
class Shape(ABC):
@abstractmethod
def area(self):
pass
class Circle(Shape):
def __init__(self, radius):
self.radius = radius
def area(self):
return math.pi * self.radius ** 2
class Rectangle(Shape):
def __init__(self, length, width):
self.length = length
self.width = width
def area(self):
return self.length * self.width
class Triangle(Shape):
def __init__(self, base, height):
self.base = base
self.height = height
def area(self):
return 0.5 * self.base * self.height
def printArea(shape):
print("The area of the shape is:", shape.area())
# Example usage
circle = Circle(5)
rectangle = Rectangle(3, 4)
triangle = Triangle(2, 6)
printArea(circle) # Output: The area of the shape is: 78.53981633974483
printArea(rectangle) # Output: The area of the shape is: 12
printArea(triangle) # Output: The area of the shape is: 6.0
```
这个程序实现了一个抽象基类`Shape`,其中定义了一个抽象方法`area()`。`Circle`、`Rectangle`和`Triangle`分别继承了`Shape`,并实现了自己的`area()`方法。在`printArea()`函数中,我们可以传入任何一个继承自`Shape`的对象,然后输出它的面积。
阅读全文