1
我使用狀態機python實現轉換。在「on_enter」回調中更改狀態時的回調順序
當我嘗試直接在on_enter回調中更改機器的狀態時,回調調用的順序不是我所期望的。
請找到最小的可運行的代碼如下,其中問題發生:
# coding: utf8
"""Minimal script."""
from transitions.extensions import GraphMachine as Machine
class MyStateMachine(object):
"""My state machine"""
def __init__(self):
"""Initialization."""
super(MyStateMachine, self).__init__()
states = ["state_a", "state_b"]
transitions = [
{
"trigger": "go_b",
"source": "state_a",
"dest": "state_b",
"before": "before",
"after": "after",
},
{
"trigger": "go_a",
"source": "state_b",
"dest": "state_a",
"before": "before",
"after": "after",
},
]
self.__machine = Machine(self, states=states, transitions=transitions,
initial="state_a")
def before(self):
"""Before transition."""
print "before transition"
def after(self):
"""After transition."""
print "after transition - current state:", self.state
def on_enter_state_a(self):
"""When entering in state A."""
print "enter state A"
def on_exit_state_a(self):
"""When exiting state A."""
print "exit state A"
def on_enter_state_b(self):
"""When entering in state A."""
print "enter state B"
self.go_a()
def on_exit_state_b(self):
"""When exiting state A."""
print "exit state B"
def main():
"""Main function."""
machine = MyStateMachine()
machine.go_b()
if __name__ == '__main__':
main()
預期輸出:
before transition
exit state A
enter state B
after transition - current state: state_b
before transition
exit state B
enter state A
after transition - current state: state_a
觀察輸出:
before transition
exit state A
enter state B
before transition
exit state B
enter state A
after transition - current state: state_a
after transition - current state: state_a
會不會是被視爲一個bug ? 如果不是,我怎麼能得到預期的輸出?