On 02/24/2014 07:30 PM, Ronaldo wrote:
How do I write a state machine in python? I have identified the states and the
conditions. Is it possible to do simple a if-then-else sort of an algorithm?
Below is some pseudo code:
if state == "ABC":
do_something()
change state to DEF
if state == "DEF"
perform_the_next_function()
...
I have a class to which certain values are passed from a GUI and the functions
above have to make use of those variables. How do I go about doing this? I have
the following algorithm:
class TestClass():
def __init__(self, var1, var2): #var1 and var2 are received from a GUI
self.var1 = var1
...
if state == "ABC"
doSomething(var1, var2)
..
Could someone point me in the right direction? Thank you!
There are probably lots of ways to do it, but I'd use a dictionary and
a variable to hold the current state:
CURRENT_STATE = "Start"
DFA_STATE_MACHINE = {"Start" : start_fn, "State1" : state1_fn, "State2" :
state2_fn ....}
#####
# Functions for each state go here. They end by setting CURRENT_STATE to some
value
#####
def start_fn():
.
.
.
def state1_fn():
.
.
.
# And so on
# Now run the state machine
while ( CURRENT_STATE != "Done"):
# Execute the function for the current state
DFA_STATE_MACHINE[CURRENT_STATE]()
Like I said, there are other - more compact ways - to do this, but this
is the general idea. Now - go do your own homework :)
--
----------------------------------------------------------------------------
Tim Daneliuk tun...@tundraware.com
PGP Key: http://www.tundraware.com/PGP/
--
https://mail.python.org/mailman/listinfo/python-list