使用python编写代码::编写一个基类 Shape,有计算对象其面积的方法 GetArea(), 计算对象周长 的方法 GetPerim() ,在此基础上派生出类 Rectangle 和 Circle,并在这两个类中 重写 GetArea()和 GetPerim。其中,Rectangle 根据边长 a,b 构造 Rectangle 对象; Circle 根据半径 r 构造 Circle 对象
时间: 2024-02-03 15:04:40 浏览: 30
以下是代码实现:
```python
import math
class Shape:
def GetArea(self):
pass
def GetPerim(self):
pass
class Rectangle(Shape):
def __init__(self, a, b):
self.a = a
self.b = b
def GetArea(self):
return self.a * self.b
def GetPerim(self):
return 2 * (self.a + self.b)
class Circle(Shape):
def __init__(self, r):
self.r = r
def GetArea(self):
return math.pi * self.r ** 2
def GetPerim(self):
return 2 * math.pi * self.r
```
在这里,我们定义了一个基类 `Shape`,其中包含了两个方法 `GetArea` 和 `GetPerim`,分别用于计算对象的面积和周长。然后我们派生出了两个类 `Rectangle` 和 `Circle`,并且重写了它们的 `GetArea` 和 `GetPerim` 方法。
在 `Rectangle` 类中,我们使用 `__init__` 方法来初始化对象的两个属性 `a` 和 `b`,然后在 `GetArea` 和 `GetPerim` 方法中按照矩形的公式计算面积和周长。
在 `Circle` 类中,我们使用 `__init__` 方法来初始化对象的属性 `r`,然后在 `GetArea` 和 `GetPerim` 方法中按照圆形的公式计算面积和周长。注意,在 `Circle` 类中我们使用了 `math` 模块中的常量 `pi` 和函数 `pow`,这需要我们在代码开头导入该模块。
相关推荐
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![rar](https://img-home.csdnimg.cn/images/20210720083606.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.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)
![](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)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)