实用工具状态机transitions
说明
1. 状态机是一个非常实用的理论。在涉及到复杂的场景,建立状态机模型,能带来极大的方便。比如,网络连接、模型状态、业务逻辑。
2. 状态机并不复杂, 重要的是它的思想,能够极大减轻复杂度。使用时关键在于定义好事件和动作。
基本概念
State: 状态
Event: 事件. 事件触发状态变换
Action: 动作. event发生前或后执行的动作
transition: 变换. 状态变换
github
https://github.com/pytransitions/transitions
安装
1 | pip install transitions |
简单示例
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 | # 连接协议状态机 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" ]() |
定义状态机
1 2 3 4 5 6 7 | # 一般都是两种:不嵌套、嵌套 from transitions import Machine #不嵌套 from transitions.extensions import HierarchicalMachine as Machine # 嵌套 # 检查状态 machine.state machine.is_<state_name>() |
定义状态
1 2 3 4 5 6 7 | # 状态可以是三种类型: 对象、字符串、字典 from transitions import State states = [ State(name = "solid" ), # 对象 "liquid" , # 字符串 { "name" : "gas" } # 字典 ] |
定义变换
1 2 3 4 5 6 7 8 9 10 | # 定义函数 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 |
2020年12月02日 18:32
Find out Reliable and Legit Ways for Extra Income from Home. You are welcome to our scam free world of online earning. legit extra income from home
2020年12月13日 20:13
Punjab National Bank is an Ideal destination for all Banking need, and PNB offer a wide range of personal banking services including loans, credit cards, savings through Internet banking facility, where PNB Netbanking is an important part of the Digital Banking platform for today, and it allows customers to access their account from anywhere and anytime, and PNB net banking is quick and convenient which gives you the liberty of not having to visit the bank branch, and you can avoid those long queues in the branches while saving enormous time and energy. Rajasthan Pay Manager
2020年12月18日 01:11
What a wonderful article, great piece of information. <a href="https://topcoupons.co/xbox-vs-ps4-one-controller-battery-life/">ps4 controller battery life</a>
2020年12月24日 15:50
Nice blog and absolutely outstanding. You can do something much better but i still say this perfect.Keep trying for the best. casino online canada
2020年12月26日 13:15
I am happy to find your distinguished way of writing the post. Now you make it easy for me to understand and implement the concept. Thank you for the post. types of government summary meaning 4 pillars of democracy
2020年12月29日 15:52
WBCHSE 12th Model Paper 2021 is released by West Bengal Council of Higher Secondary Education in the pdf form. Students appearing for West Bengal 12th Exams 2021 must practice and analyze previous year’s WBCHSE HS question papers as it will help them to become familiar with the exam pattern, marking scheme and the different styles of question that are asked in the paper. While solving the question paper they must keep in mind timing should not exceed the exam time as it will help them in finishing the exam on time. As per the previous year dates probably the exam will be held in February/March 2021. WBCHSE HS 12th Model Paper 2021 WB HS Suggestion West Bengal Council of Higher Secondary School Education WBCHSE Established in the Year 1951. The Board and Headquarters of the Board are Located in Salt Lake City, Kolkata India. WB 12th Suggestion 2021
2020年12月31日 18:26
Wow, What a Excellent post. I really found this to much informatics. It is what i was searching for.I would like to suggest you that please keep sharing such type of info.Thanks anonse transwestytów
2025年2月14日 23:42
Have you ever considered publishing an e-book or guest authoring on other sites? I have a blog based upon on the same subjects you discuss and would really like to have you share some stories/information. I know my readers would value your work. If you are even remotely interested, feel free to shoot me an email. 代写
2025年3月07日 14:24
You created some decent points there. I looked online for the issue and found most individuals should go in addition to with your internet site. Binary Signals
2025年3月11日 14:40
Wow, awesome blog structure! How long have you been running a blog for? you made blogging look easy. The total look of your site is wonderful, let alone the content material! http://www.5starsstocks.com/
2025年3月15日 18:15
I am usually to blogging and i also truly appreciate your articles. This great article has really peaks my interest. My goal is to bookmark your blog and maintain checking for brand new details. Binary Options
2025年3月21日 21:30
I really appreciate this post. I’ve been looking all over for this! Thank goodness I found it on Bing. You have made my day! Thanks again number generator
2025年3月22日 22:22
Im attempting to figure out how to subscribe to the RSS feeds, but cannot figure it out. Some help would be awesome Thanks Custom Trophies
2025年3月27日 14:39
When I originally commented I clicked the -Notify me when new surveys are added- checkbox now when a comment is added I purchase four emails using the same comment. Can there be that is it is possible to eliminate me from that service? Thanks! 바카라 사이트
2025年3月28日 00:50
This blog is perfect for anyone who want to know about this subject. You know a lot about this subject. binary options signals
2025年3月31日 19:41
I simply wished to thank you so much once more. I am not sure what I would’ve gone through without the entire methods contributed by you about such subject matter. It had been a very intimidating circumstance for me personally, nevertheless coming across a new well-written manner you resolved the issue forced me to leap for contentment. Now i’m happy for your support and trust you realize what a powerful job you were carrying out educating most people thru a web site. Most probably you haven’t encountered all of us. algorithmic trading
2025年4月01日 22:18
I just now learned your site a couple weeks ago so i are looking at it also on a daily basis. There is a massive amount information at this site and i relish your personal style belonging to the world-wide-web site very. Continue the high quality hard work! TB2X Portaal
2025年4月04日 19:23
Nice read, I just passed this onto a colleague who was doing some research on that. And he actually bought me lunch as I found it for him smile So let me rephrase that: Thank you for lunch! Udangbet