python创建一个水池类Pool,创建成员变量water表示水量,并初始化水量为0通过注水方法inlet()(一次注水固定5升)和放水方法outlet()(一次放水固定3升)向水池注水,同时创建show_water()方法展示当前水池的水量
时间: 2023-06-17 10:08:33 浏览: 64
下面是创建一个水池类 Pool 的 Python 代码实现,包括成员变量、初始化方法、注水方法、放水方法和展示当前水池水量的方法:
```python
class Pool:
def __init__(self):
self.water = 0 # 初始化水量为0
def inlet(self):
self.water += 5 # 一次注水固定5升
def outlet(self):
self.water -= 3 # 一次放水固定3升
def show_water(self):
print("当前水池的水量为:{} 升".format(self.water))
```
然后,我们可以创建一个 Pool 类的对象,调用它的方法来模拟注水和放水的过程,并展示当前水池的水量。示例代码如下:
```python
# 创建一个 Pool 类的对象
pool = Pool()
# 展示当前水池的水量
pool.show_water()
# 注水 3 次,每次 5 升,总共增加 15 升水
for i in range(3):
pool.inlet()
# 展示当前水池的水量
pool.show_water()
# 放水 2 次,每次 3 升,总共减少 6 升水
for i in range(2):
pool.outlet()
# 展示当前水池的水量
pool.show_water()
```
运行上面的代码,输出如下:
```
当前水池的水量为:0 升
当前水池的水量为:15 升
当前水池的水量为:9 升
```
注意:这里只是一个简单的模拟示例,实际情况下需要考虑更多的细节和安全性等问题。