Problem A
Water Bottle
Write a class WaterBottle which has a maximum capacity and some contents, given in liters. The corresponding attributes should be called max_capacity and current_contents.
The class should have $4$ methods:
-
__init__(max_capacity): Should accept a parameter called max_capacity with a default value of $2$, that specifies the maximum capacity of the waterbottle, and set the corresponding attribute accordingly. It should also initialize the current contents to $0L$.
-
fill(): Should fill the bottle to its maximum capacity.
-
drink(amount): Should reduce the contents of the bottle, and return the extracted amount.
-
If the amount is less than $0$, nothing changes (you are not supposed to spit into the bottle).
-
If the amount is more than the current contents, the bottle is emptied.
-
Otherwise the amount is subtracted from the contents.
-
-
__str__(): Should return a string stating how many liters of water are currently in the bottle. Print to $1$ decimal places, e.g. “$2.3L$”.
Remember that the __str__() method should never print anything, only return a string.
Note: You do not need to submit the main program as part of your solution, only the file that contains the class WaterBottle.
The following is an example main program. This example is also included in the supplied “main.py” file:
bottle = WaterBottle(5) print(f"Bottle max capacity: {bottle.max_capacity}L.") bottle.fill() print(f"Currently holding {bottle.current_contents}L of water.") sip = bottle.drink(3.7) print(f"Received {sip} liters.") print(bottle)
Output
The following is the corresponding output for the sample program given above:
Bottle max capacity: 5L. Currently holding 5.0L of water. Received 3.7 liters. The bottle currently holds 1.3L of water.