定义一个抽象基类Shape,它包含两个抽象方法diameter()、getArea(),从Shape类派生出(正方形)Square和(圆)Circle 类,这两个类都用diameter()计算对象周长,getArea()方法计算对象的面积。 编写应用程序使用Square类和Circle类。 PI取值3.14
时间: 2024-03-24 08:41:29 浏览: 156
以下是代码实现:
```python
from abc import ABCMeta, abstractmethod
import math
class Shape(metaclass=ABCMeta):
@abstractmethod
def diameter(self):
pass
@abstractmethod
def getArea(self):
pass
class Square(Shape):
def __init__(self, side):
self.side = side
def diameter(self):
return 4 * self.side
def getArea(self):
return self.side ** 2
class Circle(Shape):
def __init__(self, radius):
self.radius = radius
def diameter(self):
return 2 * math.pi * self.radius
def getArea(self):
return math.pi * self.radius ** 2
# 使用Square类和Circle类
square = Square(5)
circle = Circle(3)
print("正方形的周长为:", square.diameter())
print("正方形的面积为:", square.getArea())
print("圆的周长为:", circle.diameter())
print("圆的面积为:", circle.getArea())
```
输出结果为:
```
正方形的周长为: 20
正方形的面积为: 25
圆的周长为: 18.84955592153876
圆的面积为: 28.274333882308138
```
注意事项:
- 定义抽象基类 Shape,包含两个抽象方法 diameter 和 getArea。
- Square 和 Circle 类都继承自 Shape 类,并重写了 diameter 和 getArea 方法,实现了计算周长和面积的逻辑。
- 在使用 Square 和 Circle 类时,分别创建对象并调用其方法,计算周长和面积并输出。
阅读全文
相关推荐
![cpp](https://img-home.csdnimg.cn/images/20250102104920.png)
![rar](https://img-home.csdnimg.cn/images/20241231044955.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![rar](https://img-home.csdnimg.cn/images/20241231044955.png)
![pdf](https://img-home.csdnimg.cn/images/20241231044930.png)
![pdf](https://img-home.csdnimg.cn/images/20241231044930.png)
![pptx](https://img-home.csdnimg.cn/images/20241231044947.png)
![zip](https://img-home.csdnimg.cn/images/20241231045053.png)