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

yipeiwu_com5年前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程序设计有所帮助。

相关文章

Python数据结构之双向链表的定义与使用方法示例

Python数据结构之双向链表的定义与使用方法示例

本文实例讲述了Python数据结构之双向链表的定义与使用方法。分享给大家供大家参考,具体如下: 和单链表类似,只不过是增加了一个指向前面一个元素的指针而已。 示意图: python 实...

python实现自动化报表功能(Oracle/plsql/Excel/多线程)

python实现自动化报表功能(Oracle/plsql/Excel/多线程)

日常会有很多固定报表需要手动更新,本文将利用python实现多线程运行oracle代码,并利用xlwings包和numpy包将结果写入到指定excel模版(不改变模版内容),并自动生成带...

100行Python代码实现自动抢火车票(附源码)

100行Python代码实现自动抢火车票(附源码)

前言 又要过年了,今年你不妨自己写一段代码来抢回家的火车票,是不是很Cool。下面话不多说了,来一起看看详细的介绍吧。 先准备好: 12306网站用户名和密码 chrome浏览...

python 扩展print打印文件路径和当前时间信息的实例代码

pinrt函数我们经常使用,但是有时候python自带的print函数打印的信息不够详细,我们可以扩展一下,打印更多的信息,例如程序文件绝对路径、当前日期时间、消息等等。这里我参考了yd...

postman传递当前时间戳实例详解

postman传递当前时间戳实例详解

请求动态参数(例如时间戳) 有时我们在请求接口时,需要带上当前时间戳这种动态参数,那么postman能不能自动的填充上呢。 我们可以使用postman的pre-request scrip...