定义一个抽象类Shape,它包含一个抽象方法getArea(),从Shape类派生出Rectangle和Circle类,这两个类都用getArea()方法计算对象的面积。编写应用程序使用Rectang...
时间: 2024-03-07 22:47:40 浏览: 19
好的,你的问题是关于面向对象编程的。下面是代码实现:
```python
import math
# 定义一个抽象类 Shape
class Shape:
def getArea(self):
pass
# Rectangle 类继承自 Shape 类
class Rectangle(Shape):
def __init__(self, width, height):
self.width = width
self.height = height
def getArea(self):
return self.width * self.height
# Circle 类继承自 Shape 类
class Circle(Shape):
def __init__(self, radius):
self.radius = radius
def getArea(self):
return math.pi * self.radius ** 2
# 应用程序
r = Rectangle(5, 10)
c = Circle(3)
print("Rectangle 面积:", r.getArea())
print("Circle 面积:", c.getArea())
```
运行结果:
```
Rectangle 面积: 50
Circle 面积: 28.274333882308138
```
在这个例子中,我们定义了一个抽象类 Shape,其中包含了一个抽象方法 getArea()。我们从 Shape 类派生出两个子类 Rectangle 和 Circle,这两个类都实现了 getArea() 方法来计算对象的面积。在应用程序中,我们创建了一个 Rectangle 对象和一个 Circle 对象,并分别调用它们的 getArea() 方法来计算它们的面积。