Created
July 29, 2017 07:19
-
-
Save Karn/188603e62c5fda66a42995e11b3653bc to your computer and use it in GitHub Desktop.
Python State Machine - States
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
class State(object): | |
""" | |
We define a state object which provides some utility functions for the | |
individual states within the state machine. | |
""" | |
def __init__(self): | |
print 'Processing current state:', str(self) | |
def on_event(self, event): | |
""" | |
Handle events that are delegated to this State. | |
""" | |
pass | |
def __repr__(self): | |
""" | |
Leverages the __str__ method to describe the State. | |
""" | |
return self.__str__() | |
def __str__(self): | |
""" | |
Returns the name of the State. | |
""" | |
return self.__class__.__name__ | |
# Start of our states | |
class LockedState(State): | |
""" | |
The state which indicates that there are limited device capabilities. | |
""" | |
def on_event(self, event): | |
if event == 'pin_entered': | |
return UnlockedState() | |
return self | |
class UnlockedState(State): | |
""" | |
The state which indicates that there are no limitations on device | |
capabilities. | |
""" | |
def on_event(self, event): | |
if event == 'device_locked': | |
return LockedState() | |
return self | |
# End of our states. |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment