说明
1. 状态机是一个非常实用的理论。在涉及到复杂的场景,建立状态机模型,能带来极大的方便。比如,网络连接、模型状态、业务逻辑。
2. 状态机并不复杂, 重要的是它的思想,能够极大减轻复杂度。使用时关键在于定义好事件和动作。
基本概念
state: 状态
event: 事件. 事件触发状态变换
action: 动作. event发生前或后执行的动作
transition: 变换. 状态变换
github
安装
pip install transitions
简单示例
# 连接协议状态机
from transitions.extensions import hierarchicalmachine as machine
from transitions.extensions.nesting import nestedstate
class connectionstatemachine:
"""connection state machine."""
def __init__(self, callbacks=none):
"""
:param callbacks: callbacks for the state machine
"""
self.callbacks = {}
# 定义状态
self.states = ["state_not_connected",
{
'name': "state_connected", # 状态名
'on_enter': self._on_enter_connected, # 进入状态触发
'on_exit': self._on_exit_connected, # 退出状态触发
'children': [ # 状态嵌套
"state_not_selected",
{
'name': "state_selected",
'on_enter': self._on_enter_connected_selected
}
]
}]
# transition 1
self.machine = machine(model=self, states=self.states, initial="state_not_connected", auto_transitions=false)
if callbacks:
self.callbacks = callbacks
# 定义状态变换
self.machine.add_transition('connect', "state_not_connected", "state_connected_not_selected") # transition 2
self.machine.add_transition('disconnect', "state_connected", "state_not_connected") # transition 3
self.machine.add_transition('select', "state_connected_not_selected", "state_connected_selected") # transition 4
self.machine.add_transition('deselect', "state_connected_selected", "state_connected_not_selected") # transition 5
self.machine.add_transition('timeoutt7', "state_connected_not_selected", "state_not_connected") # transition 6
# 事件触发的动作
def _on_enter_connected(self):
if "on_enter_connected" in self.callbacks:
self.callbacks["on_enter_connected"]()
def _on_exit_connected(self):
if "on_exit_connected" in self.callbacks:
self.callbacks["on_exit_connected"]()
def _on_enter_connected_selected(self):
if "on_enter_connected_selected" in self.callbacks:
self.callbacks["on_enter_connected_selected"]()
定义状态机
# 一般都是两种:不嵌套、嵌套
from transitions import machine #不嵌套
from transitions.extensions import hierarchicalmachine as machine # 嵌套
# 检查状态
machine.state
machine.is_()
定义状态
# 状态可以是三种类型: 对象、字符串、字典
from transitions import state
states = [
state(name="solid"), # 对象
"liquid", # 字符串
{"name": "gas"} # 字典
]
定义变换
# 定义函数
machine.add_transition(trigger, source, dest, )
trigger(str) 方法名,触发状态转换
source(str or list) 源状态
dest(str) 目标状态
# 加上变换
machine.add_transition(trigger="wake_up", source="asleep", dest="hanging out")
machine.add_transition('work_out', 'hanging out', 'hungry')
machine.add_transition('nap', '*', 'asleep') # 从任意状态变为asleep
以上就是python 实用工具状态机transitions的详细内容,更多关于python transitions的资料请关注萬仟网其它相关文章!
希望与广大网友互动??
点此进行留言吧!