为什么这段代码显然不能正常工作?
下面的机器有两种状态:idle
和travelling
,以及两个名为go
的转换。我使用register_handlers
附加到此转换on_enter
和on_go
处理程序。我希望这段代码的结果是两个打印,每个处理程序之一。出于某种原因,似乎只有on_enter处理程序被执行。
import pysm
machine = pysm.pysm.StateMachine('ship')
idle = pysm.pysm.State('idle')
class TravellingState(pysm.pysm.State):
def on_go(self, state, event):
print("on_go function called")
def on_enter(self, state, event):
print("on_enter function called")
def register_handlers(self):
self.handlers = {
'enter': self.on_enter,
'go': self.on_go, # doesnt work?
}
travelling = TravellingState('travelling')
machine.add_state(idle, initial=True)
machine.add_state(travelling)
machine.add_transition(from_state=idle, to_state=travelling, events=['go'])
machine.initialize()
machine.dispatch(pysm.pysm.Event('go', cargo={'target':(1,1)}))
答案 0 :(得分:0)
go
是travelling
州将处理的事件。
但是你最初处于idle
状态。它会忽略go
事件。
您已在idle
事件中创建了从travelling
到go
的转换。因此,您基本上看到的是从idle
到travelling
的转换,因此调用enter
实例中的Travelling
处理程序。
如果要在go
状态下处理idle
,请在idle
实例中指定处理程序:
def on_go(state, event):
print('on_go from idle')
idle = pysm.pysm.State('idle')
idle.handlers = {'go': on_go}
然后致电
machine.dispatch(pysm.pysm.Event('go', cargo={'target':(1,1)}))
调用on_go
状态的idle
处理程序。
同时强>
保留您的代码,如果您再次调用go
事件(已处于travelling
状态),则会调用您的处理程序。
machine.dispatch(pysm.pysm.Event('go', cargo={'target':(1,1)}))
完整的工作示例:
import pysm
machine = pysm.pysm.StateMachine('ship')
def on_go(state, event):
print('on_go from idle')
idle = pysm.pysm.State('idle')
idle.handlers = {'go': on_go}
class TravellingState(pysm.pysm.State):
def on_go(self, state, event):
print("on_go from travelling")
def on_enter(self, state, event):
print("on_enter from travelling")
def register_handlers(self):
self.handlers = {
'enter': self.on_enter,
'go': self.on_go,
}
travelling = TravellingState('travelling')
machine.add_state(idle, initial=True)
machine.add_state(travelling)
machine.add_transition(from_state=idle, to_state=travelling, events=['go'])
machine.initialize()
machine.dispatch(pysm.pysm.Event('go', cargo={'target':(1,1)}))
machine.dispatch(pysm.pysm.Event('go', cargo={'target':(1,1)}))
正如预期的那样输出:
# go event is dispatched
on_go from idle
# Now the transition happens
on_enter from travelling
# go is dispatched again
on_go from travelling