-
Notifications
You must be signed in to change notification settings - Fork 0
/
encapsulation.py
67 lines (53 loc) · 1.84 KB
/
encapsulation.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
class TankError(Exception):
pass
class Tank:
def __init__(self, capacity):
self.capacity = capacity
self.__level = 0
@property
def level(self):
return self.__level
@level.setter
def level(self, amount):
if amount > 0:
# fueling
if amount <= self.capacity:
self.__level = amount
else:
raise TankError('Too much liquid in the tank')
elif amount < 0:
raise TankError('Not possible to set negative liquid level')
@level.deleter
def level(self):
if self.__level > 0:
print('It is good to remember to sanitize the remains from the tank!')
self.__level = None
# our_tank object has a capacity of 20 units
our_tank = Tank(20)
# our_tank's current liquid level is set to 10 units
our_tank.level = 10
our_tank.__level=1
print('Current liquid level:', our_tank.level)
# adding additional 3 units (setting liquid level to 13)
our_tank.level += 3
print('Current liquid level:', our_tank.level)
# let's try to set the current level to 21 units
# this should be rejected as the tank's capacity is 20 units
try:
our_tank.level = 21
except TankError as e:
print('Trying to set liquid level to 21 units, result:', e)
# similar example - let's try to add an additional 15 units
# this should be rejected as the total capacity is 20 units
try:
our_tank.level += 15
except TankError as e:
print('Trying to add an additional 15 units, result:', e)
# let's try to set the liquid level to a negative amount
# this should be rejected as it is senseless
try:
our_tank.level = -3
except TankError as e:
print('Trying to set liquid level to -3 units, result:', e)
print('Current liquid level:', our_tank.level)
del our_tank.level