• linkedu视频
  • 平面设计
  • 电脑入门
  • 操作系统
  • 办公应用
  • 电脑硬件
  • 动画设计
  • 3D设计
  • 网页设计
  • CAD设计
  • 影音处理
  • 数据库
  • 程序设计
  • 认证考试
  • 信息管理
  • 信息安全
菜单
linkedu.com
  • 网页制作
  • 数据库
  • 程序设计
  • 操作系统
  • CMS教程
  • 游戏攻略
  • 脚本语言
  • 平面设计
  • 软件教程
  • 网络安全
  • 电脑知识
  • 服务器
  • 视频教程
  • vbs
  • DOS/BAT
  • hta/htc
  • python
  • perl
  • VBA
  • ColdFusion
  • ruby
  • PowerShell
  • Lua
  • Golang
  • linux shell
您的位置:首页 > 脚本语言 >python > Python实现简单状态框架的方法

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

作者: 字体:[增加 减小] 来源:互联网

通过本文主要向大家介绍了python 状态机,python多进程状态,python 文件状态,python http 状态码,python web框架等相关知识,希望对您有所帮助,也希望大家支持linkedu.com www.linkedu.com

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

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

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()")
  &

您可能想查找下面的文章:

  • Python检测QQ在线状态的方法
  • Python实现简单状态框架的方法
  • 使用python检测手机QQ在线状态的脚本代码

相关文章

  • python通过装饰器检查函数参数数据类型的方法
  • python读文件逐行处理的示例代码分享
  • 在IIS服务器上以CGI方式运行Python脚本的教程
  • Python环境变量设置方法
  • 使用Python的Scrapy框架编写web爬虫的简单示例
  • Python实现统计英文单词个数及字符串分割代码
  • python Django框架实现自定义表单提交
  • python机器学习库xgboost的使用
  • Mac OS X10.9安装的Python2.7升级Python3.3步骤详解
  • python实现马耳可夫链算法实例分析

文章分类

  • vbs
  • DOS/BAT
  • hta/htc
  • python
  • perl
  • VBA
  • ColdFusion
  • ruby
  • PowerShell
  • Lua
  • Golang
  • linux shell

最近更新的内容

    • python字符串对其居中显示的方法
    • Python中使用ConfigParser解析ini配置文件实例
    • Python爬取三国演义的实现方法
    • 在IIS服务器上以CGI方式运行Python脚本的教程
    • 使用Python脚本将绝对url替换为相对url的教程
    • python实现DES加密解密方法实例详解
    • 基于python yield机制的异步操作同步化编程模型
    • 使用C#配合ArcGIS Engine进行地理信息系统开发
    • 详细解读Python的web.py框架下的application.py模块
    • python轻松实现代码编码格式转换

关于我们 - 联系我们 - 免责声明 - 网站地图

©2020-2025 All Rights Reserved. linkedu.com 版权所有