2.定义一个长方形Rect类,派生出长方体Cub,计算派生类的对象的表面积和体积。测试用例:长方形的长为10,宽为20,长方体的高为10。
时间: 2024-05-15 12:12:23 浏览: 6
以下是代码实现:
```python
class Rect:
def __init__(self, length, width):
self.length = length
self.width = width
def area(self):
return self.length * self.width
class Cub(Rect):
def __init__(self, length, width, height):
super().__init__(length, width)
self.height = height
def surface_area(self):
return 2 * (self.length * self.width + self.width * self.height + self.height * self.length)
def volume(self):
return self.length * self.width * self.height
# 测试用例
rect = Rect(10, 20)
cub = Cub(10, 20, 10)
print("长方形的面积为:", rect.area())
print("长方体的表面积为:", cub.surface_area())
print("长方体的体积为:", cub.volume())
```
输出结果:
```
长方形的面积为: 200
长方体的表面积为: 1200
长方体的体积为: 2000
```
相关推荐
![doc](https://img-home.csdnimg.cn/images/20210720083327.png)
![zip](https://img-home.csdnimg.cn/images/20210720083736.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)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)