python 实用工具状态机transitions

作者:妙音 时间:2023-11-06 21:53:41 

说明 

1. 状态机是一个非常实用的理论。在涉及到复杂的场景,建立状态机模型,能带来极大的方便。比如,网络连接、模型状态、业务逻辑。 
2. 状态机并不复杂, 重要的是它的思想,能够极大减轻复杂度。使用时关键在于定义好事件和动作。 

基本概念 

  • State: 状态

  • Event: 事件. 事件触发状态变换

  • Action: 动作. event发生前或后执行的动作

  • transition: 变换. 状态变换

github

https://github.com/pytransitions/transitions

安装


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_<state_name>()

定义状态


# 状态可以是三种类型: 对象、字符串、字典
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

来源:http://yongqing.is-programmer.com/posts/215592.html

标签:python,transitions,工具,状态机
0
投稿

猜你喜欢

  • 与MSSQL对比学习MYSQL的心得(四)--BLOB数据类型

    2024-01-20 12:32:53
  • 对Python中for复合语句的使用示例讲解

    2023-07-19 17:50:44
  • Vue2 配置 Axios api 接口调用文件的方法

    2024-05-05 09:08:37
  • Python3.x和Python2.x的区别介绍

    2022-01-05 12:36:27
  • 查看修改MySQL表结构命令

    2024-01-26 03:45:52
  • python urllib.request模块的使用详解

    2023-03-27 18:19:15
  • Python 按字典dict的键排序,并取出相应的键值放于list中的实例

    2022-01-26 16:48:46
  • 一文彻底理清session、cookie、token的区别

    2024-01-02 06:16:29
  • 使用MySQL内建复制功能

    2009-12-15 21:36:00
  • sqlserver 复制表 复制数据库存储过程的方法

    2024-01-21 17:01:00
  • MySQL获取系统性能和状态代码

    2024-01-13 10:56:18
  • 让ASP搭配MYSQL

    2009-10-04 20:30:00
  • SQL Server中检查字段的值是否为数字的方法

    2024-01-24 17:47:21
  • Python translator使用实例

    2021-02-09 22:40:24
  • 使用Python实现二终端网络可靠度

    2021-03-25 17:39:40
  • Python学习之集合set

    2021-07-25 10:44:34
  • python中的 zip函数详解及用法举例

    2023-04-16 15:31:36
  • python OpenCV学习笔记之绘制直方图的方法

    2023-06-04 02:34:38
  • python基于itchat模块实现微信防撤回

    2022-03-15 01:41:42
  • python识别围棋定位棋盘位置

    2023-01-09 01:49:34
  • asp之家 网络编程 m.aspxhome.com