定义一个抽象类 Shape,它包含一个抽象方法 getArea(),从 Shape 类 派生出 Rectangle 和 Circle 类,这两个类都用 getArea()方法计算对象 的面积。编写应用程序使用 Rectange 和 Circle 类。
时间: 2023-11-28 11:49:17 浏览: 138
以下是实现 Shape 抽象类和 Rectangle、Circle 类的 Python 代码示例:
```python
from abc import ABC, abstractmethod
import math
class Shape(ABC):
@abstractmethod
def getArea(self):
pass
class Rectangle(Shape):
def __init__(self, width, height):
self.width = width
self.height = height
def getArea(self):
return self.width * self.height
class Circle(Shape):
def __init__(self, radius):
self.radius = radius
def getArea(self):
return math.pi * self.radius ** 2
# 应用程序示例
rect = Rectangle(5, 10)
print("矩形的面积为:", rect.getArea())
circle = Circle(3)
print("圆的面积为:", circle.getArea())
```
在上述代码中,我们定义了 Shape 抽象类,并使用 @abstractmethod 装饰器将 getArea() 方法声明为抽象方法。然后定义了 Rectangle 和 Circle 两个子类,它们都继承自 Shape 类,并实现了 getArea() 方法。
最后在应用程序中,我们创建了一个 Rectangle 类的对象 rect 和一个 Circle 类的对象 circle,并分别调用它们的 getArea() 方法来计算它们的面积。
阅读全文
相关推荐


















