[python-users] State Machine

M.-A. Lemburg mal at egenix.com
Di Feb 11 20:29:15 CET 2014


On 11.02.2014 20:11, Dirk Hünniger wrote:
> Hallo,
> ich musste neulich auf der Arbeit eine State Machine in Python bauen. Meine erste Idee war ein
> switch case statement. Habe in Python jedoch keines gefunden und daher so emuliert.
> Hat noch jemand eine schönere Idee?

Hier gibt es eine ganze Reihe solcher FSMs:

https://wiki.python.org/moin/FiniteStateMachine

Ein Artikel von David Mertz zum Thema:

http://www.ibm.com/developerworks/linux/library/l-python-state/index.html

Und eine State Machine, mit der man Text parsen kann: die Tagging
Engine in mxTextTools:

http://www.egenix.com/products/python/mxBase/mxTextTools/

Deine Variante ist etwas ungewöhnlich, da Du eine Methode umbiegst
um Zustandsänderungen zu "speichern". Normalerweise macht man das
über ein Attribute, das neue Werte bekommt und verzweigt dann entsprechend
dem Attributwert.

> Viele Grüße Dirk
> 
> import time
> class Motor:
>   def __init__(self):
>     self.position=50
>     self.zustand = self.referenzfahrt
>   def forward(self):
>     self.position+=10
>     print self.position
>   def backward(self):
>     self.position-=10
>     print self.position
>   def referenzfahrt(self):
>     self.forward()
>     time.sleep(0.2)
>     if self.position>90:
>       self.zustand=self.bereit_zum_fahren
>   def bereit_zum_fahren(self):
>     raw_input("Bereit bitte Taste druecken")
>     self.zustand=self.fahrt
>   def fahrt(self):
>     self.backward()
>     time.sleep(0.2)
>     if self.position<10:
>       self.zustand=self.pause
>   def pause(self):
>     print "pause"
>     time.sleep(1.0)
>     self.zustand=self.referenzfahrt
> m=Motor()
> while True:
>   m.zustand()

-- 
Marc-Andre Lemburg
eGenix.com

Professional Python Services directly from the Source  (#1, Feb 11 2014)
>>> Python Projects, Consulting and Support ...   http://www.egenix.com/
>>> mxODBC.Zope/Plone.Database.Adapter ...       http://zope.egenix.com/
>>> mxODBC, mxDateTime, mxTextTools ...        http://python.egenix.com/
________________________________________________________________________

::::: Try our mxODBC.Connect Python Database Interface for free ! ::::::

   eGenix.com Software, Skills and Services GmbH  Pastor-Loeh-Str.48
    D-40764 Langenfeld, Germany. CEO Dipl.-Math. Marc-Andre Lemburg
           Registered at Amtsgericht Duesseldorf: HRB 46611
               http://www.egenix.com/company/contact/



Mehr Informationen über die Mailingliste python-users