代码
from transitions import Machine
# 定义类
class Matter(object):
pass
model = Matter()
# 状态定义
states=['New', 'Ready', 'Waiting', 'Running','Terminated']
# 定义状态转移
transitions = [
{'trigger': 'Admitted', 'source': 'New', 'dest': 'Ready' },
{'trigger': 'Dispatch', 'source': 'Ready', 'dest': 'Running'},
{'trigger': 'Interrupt', 'source': 'Running', 'dest': 'Ready'},
{'trigger': 'InputOutputoreventwait', 'source': 'Running', 'dest': 'Waiting'},
{'trigger': 'InputOutputoreventcompletion', 'source': 'Waiting', 'dest': 'Ready'},
{'trigger': 'Exit', 'source': 'Running', 'dest': 'Terminated'}]
# 初始化
machine = Machine(model=model, states=states, transitions=transitions, initial='New')
# Test
print(model.state) # New
# 状态转变的完整流程
model.Admitted()
print(model.state)
model.Dispatch()
print(model.state)
model.Interrupt()
print(model.state)
model.Dispatch()
print(model.state)
model.InputOutputoreventwait()
print(model.state)
model.InputOutputoreventcompletion()
print(model.state)
model.Dispatch()
print(model.state)
model.Exit()
运行
![](https://img2020.cnblogs.com/blog/2551217/202111/2551217-20211127201931161-494551090.png)