forked from onionmccabbage/beyondAdvancedPythonApril2021
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmy_state.py
43 lines (37 loc) · 1.09 KB
/
my_state.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
class ComputerState(object):
name = 'state'
allowed = []
def switch(self, state):
if state.name in self.allowed:
print('Current: {} switching to: {}'.format(self, state.name))
self.__class__ = state
else:
print('Current: {} cannot switch to {}'.format(self, self.name))
def __str__(self):
return self.name
class On(ComputerState):
name = 'on'
allowed = ['off', 'suspend', 'hibernate']
class Off(ComputerState):
name = 'off'
allowed = ['on']
class Suspend(ComputerState):
name = 'suspend'
allowed = ['on']
class Hibernate(ComputerState):
name = 'hibernate'
allowed = ['on']
class Computer():
def __init__(self, model='super duper'):
self.model = model
self.state = Off()
def change(self, state):
self.state.switch(state)
if __name__ == '__main__':
comp = Computer()
comp.change(On)
comp.change(Off)
comp.change(On)
comp.change(Suspend)
# next line should fail to change state
comp.change(Hibernate)