定义学生类Student,包括学号,姓名,waterCount,模拟学生喝水过程,要求输出每次喝水量,剩余水量,如不够喝也要给出提示。(注:学生共用水量100L,所有学生共享100L水,至少建立2个学生对象来模拟喝水过程)
时间: 2024-05-15 15:18:07 浏览: 122
好的,让我来回答你的问题。下面是定义学生类Student的代码:
```python
class Student:
water_shared = 100
def __init__(self, student_id, name):
self.student_id = student_id
self.name = name
self.waterCount = 0
def drinkWater(self, amount):
if amount > Student.water_shared:
print("水不够喝,请等一下再来喝")
return
else:
self.waterCount += amount
Student.water_shared -= amount
print(self.name + "喝了" + str(amount) + "L水,剩余" + str(Student.water_shared) +"L水。")
# 创建两个学生对象
s1 = Student("001", "小明")
s2 = Student("002", "小丽")
# 模拟学生喝水过程
s1.drinkWater(50)
s2.drinkWater(30)
s1.drinkWater(40)
s2.drinkWater(50)
```
假设s1先喝了50L水,s2后喝了30L水,此时剩余水量为20L。接着s1再喝了40L水,此时剩余水量为0L,s2再喝水时会提示“水不够喝,请等一下再来喝”。
阅读全文