python 设计一个立方体类Box,定义三个属性,分别是长,宽,高。定义二个方法,分别计算并输出立方体的体积和表面积
时间: 2023-06-11 19:06:06 浏览: 213
可以按照以下代码实现:
```python
class Box:
def __init__(self, length, width, height):
self.length = length
self.width = width
self.height = height
def get_volume(self):
volume = self.length * self.width * self.height
print(f"The volume of the box is {volume}.")
def get_surface_area(self):
surface_area = 2 * (self.length*self.width + self.length*self.height + self.width*self.height)
print(f"The surface area of the box is {surface_area}.")
```
在上面的代码中,我们定义了一个名为 `Box` 的类,该类有三个属性:`length`、`width` 和 `height`,分别表示立方体的长、宽和高。然后,我们定义了两个方法,`get_volume` 和 `get_surface_area`,分别用于计算和输出立方体的体积和表面积。在 `get_volume` 方法中,我们使用立方体的长、宽和高计算出立方体的体积,并输出结果。在 `get_surface_area` 方法中,我们使用立方体的长、宽和高计算出立方体的表面积,并输出结果。
接下来,我们可以创建一个 `Box` 对象,并调用其方法来计算和输出立方体的体积和表面积。例如:
```python
my_box = Box(3, 4, 5)
my_box.get_volume() # 输出:The volume of the box is 60.
my_box.get_surface_area() # 输出:The surface area of the box is 94.
```
在上面的示例中,我们创建了一个 `Box` 对象 `my_box`,并将其长、宽和高分别设置为 3、4 和 5。然后,我们分别调用了 `get_volume` 和 `get_surface_area` 方法来计算和输出立方体的体积和表面积。