Python实现简单状态框架的方法

 更新时间:2015年03月19日 16:18:32   作者:chongq  
这篇文章主要介绍了Python实现简单状态框架的方法,涉及Python状态框架的实现技巧,具有一定参考借鉴价值,需要的朋友可以参考下

本文实例讲述了Python实现简单状态框架的方法。分享给大家供大家参考。具体分析如下:

这里使用Python实现一个简单的状态框架,代码需要在python3.2环境下运行

复制代码 代码如下:
from time import sleep
from random import randint, shuffle
class StateMachine(object):
    ''' Usage:  Create an instance of StateMachine, use set_starting_state(state) to give it an
        initial state to work with, then call tick() on each second (or whatever your desired
        time interval might be. '''
    def set_starting_state(self, state):
        ''' The entry state for the state machine. '''
        state.enter()
        self.state = state
    def tick(self):
        ''' Calls the current state's do_work() and checks for a transition '''
        next_state = self.state.check_transitions()
        if next_state is None:
            # Stick with this state
            self.state.do_work()
        else:
            # Next state found, transition to it
            self.state.exit()
            next_state.enter()
            self.state = next_state
class BaseState(object):
    ''' Usage: Subclass BaseState and override the enter(), do_work(), and exit() methods.
            enter()    -- Setup for your state should occur here.  This likely includes adding
                          transitions or initializing member variables.
            do_work()  -- Meat and potatoes of your state.  There may be some logic here that will
                          cause a transition to trigger.
            exit()     -- Any cleanup or final actions should occur here.  This is called just
                          before transition to the next state.
    '''
    def add_transition(self, condition, next_state):
        ''' Adds a new transition to the state.  The "condition" param must contain a callable
            object.  When the "condition" evaluates to True, the "next_state" param is set as
            the active state. '''
        # Enforce transition validity
        assert(callable(condition))
        assert(hasattr(next_state, "enter"))
        assert(callable(next_state.enter))
        assert(hasattr(next_state, "do_work"))
        assert(callable(next_state.do_work))
        assert(hasattr(next_state, "exit"))
        assert(callable(next_state.exit))
        # Add transition
        if not hasattr(self, "transitions"):
            self.transitions = []
        self.transitions.append((condition, next_state))
    def check_transitions(self):
        ''' Returns the first State thats condition evaluates true (condition order is randomized) '''
        if hasattr(self, "transitions"):
            shuffle(self.transitions)
            for transition in self.transitions:
                condition, state = transition
                if condition():
                    return state
    def enter(self):
        pass
    def do_work(self):
        pass
    def exit(self):
        pass
##################################################################################################
############################### EXAMPLE USAGE OF STATE MACHINE ###################################
##################################################################################################
class WalkingState(BaseState):
    def enter(self):
        print("WalkingState: enter()")
        def condition(): return randint(1, 5) == 5
        self.add_transition(condition, JoggingState())
        self.add_transition(condition, RunningState())
    def do_work(self):
        print("Walking...")
    def exit(self):
        print("WalkingState: exit()")
class JoggingState(BaseState):
    def enter(self):
        print("JoggingState: enter()")
        self.stamina = randint(5, 15)
        def condition(): return self.stamina <= 0
        self.add_transition(condition, WalkingState())
    def do_work(self):
        self.stamina -= 1
        print("Jogging ({0})...".format(self.stamina))
    def exit(self):
        print("JoggingState: exit()")
class RunningState(BaseState):
    def enter(self):
        print("RunningState: enter()")
        self.stamina = randint(5, 15)
        def walk_condition(): return self.stamina <= 0
        self.add_transition(walk_condition, WalkingState())
        def trip_condition(): return randint(1, 10) == 10
        self.add_transition(trip_condition, TrippingState())
    def do_work(self):
        self.stamina -= 2
        print("Running ({0})...".format(self.stamina))
    def exit(self):
        print("RunningState: exit()")
class TrippingState(BaseState):
    def enter(self):
        print("TrippingState: enter()")
        self.tripped = False
        def condition(): return self.tripped
        self.add_transition(condition, WalkingState())
    def do_work(self):
        print("Tripped!")
        self.tripped = True
    def exit(self):
        print("TrippingState: exit()")
if __name__ == "__main__":
    state = WalkingState()
    state_machine = StateMachine()
    state_machine.set_starting_state(state)
    while True:
        state_machine.tick()
        sleep(1)

希望本文所述对大家的Python程序设计有所帮助。

相关文章

  • selenium WebDriverWait类等待机制的实现

    selenium WebDriverWait类等待机制的实现

    这篇文章主要介绍了selenium WebDriverWait类等待机制的实现,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友们下面随着小编来一起学习学习吧
    2020-03-03
  • Python3网络爬虫中的requests高级用法详解

    Python3网络爬虫中的requests高级用法详解

    本节我们再来了解下 Requests 的一些高级用法,如文件上传,代理设置,Cookies 设置等等。感兴趣的朋友跟随小编一起看看吧
    2019-06-06
  • Python数据处理Filter函数高级用法示例

    Python数据处理Filter函数高级用法示例

    本文将详细介绍filter函数的使用方法,并提供丰富的示例代码,帮助你深入理解如何利用它来处理数据,有需要的朋友可以借鉴参考下,希望能够有所帮助,祝大家多多进步,早日升职加薪
    2023-11-11
  • 浅析Python编写函数装饰器

    浅析Python编写函数装饰器

    这篇文章主要介绍了Python编写函数装饰器的相关资料,需要的朋友可以参考下
    2016-03-03
  • Python脚本去除文件的只读性操作

    Python脚本去除文件的只读性操作

    这篇文章主要介绍了Python脚本去除文件的只读性操作,具有很好的参考价值,希望对大家有所帮助。一起跟随小编过来看看吧
    2020-03-03
  • 解读残差网络(Residual Network),残差连接(skip-connect)

    解读残差网络(Residual Network),残差连接(skip-connect)

    这篇文章主要介绍了残差网络(Residual Network),残差连接(skip-connect),具有很好的参考价值,希望对大家有所帮助,如有错误或未考虑完全的地方,望不吝赐教
    2023-08-08
  • Python pass语句作用和Python assert断言函数的用法

    Python pass语句作用和Python assert断言函数的用法

    这篇文章主要介绍了Python pass语句作用和Python assert断言函数的用法,文章内容介绍详细具有一定的参考价值,需要的小伙伴可以参考一下,希望对你有所帮助
    2022-03-03
  • Python 2/3下处理cjk编码的zip文件的方法

    Python 2/3下处理cjk编码的zip文件的方法

    今天小编给大家分享Python 2/3下处理cjk编码的zip文件的方法,在项目中经常会遇到这样的问题,小编特意分享到脚本之家平台,感兴趣的朋友跟随小编一起看看吧
    2019-04-04
  • 深度学习详解之初试机器学习

    深度学习详解之初试机器学习

    机器学习可应用在各个方面,本篇将在系统性进入机器学习方向前,初步认识机器学习,利用线性回归预测波士顿房价,让我们一起来看看吧
    2021-04-04
  • python 编码规范整理

    python 编码规范整理

    这篇文章主要介绍了python 编码规范整理,需要的朋友可以参考下
    2018-05-05

最新评论