Python實(shí)現(xiàn)簡單狀態(tài)框架的方法
本文實(shí)例講述了Python實(shí)現(xiàn)簡單狀態(tài)框架的方法。分享給大家供大家參考。具體分析如下:
這里使用Python實(shí)現(xiàn)一個(gè)簡單的狀態(tài)框架,代碼需要在python3.2環(huán)境下運(yùn)行
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程序設(shè)計(jì)有所幫助。
- Python獲取電腦硬件信息及狀態(tài)的實(shí)現(xiàn)方法
- python獲取網(wǎng)頁狀態(tài)碼示例
- python檢測lvs real server狀態(tài)
- python實(shí)現(xiàn)系統(tǒng)狀態(tài)監(jiān)測和故障轉(zhuǎn)移實(shí)例方法
- 在python的WEB框架Flask中使用多個(gè)配置文件的解決方法
- 10款最好的Web開發(fā)的 Python 框架
- 分享15個(gè)最受歡迎的Python開源框架
- 全面解讀Python Web開發(fā)框架Django
- python中日期和時(shí)間格式化輸出的方法小結(jié)
- python通過colorama模塊在控制臺輸出彩色文字的方法
相關(guān)文章
python實(shí)現(xiàn)梯度法 python最速下降法
這篇文章主要為大家詳細(xì)介紹了python梯度法,最速下降法的原理,文中示例代碼介紹的非常詳細(xì),具有一定的參考價(jià)值,感興趣的小伙伴們可以參考一下2020-03-03
python實(shí)現(xiàn)數(shù)據(jù)挖掘中分箱的示例代碼
數(shù)據(jù)分箱(英語:Data?binning)是一種數(shù)據(jù)預(yù)處理方法,用于最大限度地減少小觀測誤差的影響,本文主要為大家介紹了python實(shí)現(xiàn)數(shù)據(jù)分箱的相關(guān)知識,感興趣的可以了解下2024-01-01
Django框架安裝及項(xiàng)目創(chuàng)建過程解析
這篇文章主要介紹了Django框架安裝及項(xiàng)目創(chuàng)建過程解析,文中通過示例代碼介紹的非常詳細(xì),對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友可以參考下2020-09-09
Python實(shí)現(xiàn)"驗(yàn)證回文串"的幾種方法
這篇文章主要介紹了Python實(shí)現(xiàn)"驗(yàn)證回文串"的幾種方法,文中通過示例代碼介紹的非常詳細(xì),對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧2021-03-03
解決python問題 Traceback (most recent call&n
這篇文章主要介紹了解決python問題 Traceback (most recent call last),具有很好的參考價(jià)值,希望對大家有所幫助。如有錯誤或未考慮完全的地方,望不吝賜教2022-12-12
Python基于Floyd算法求解最短路徑距離問題實(shí)例詳解
這篇文章主要介紹了Python基于Floyd算法求解最短路徑距離問題,結(jié)合完整實(shí)例形式詳細(xì)分析了Python使用Floyd算法求解最短路徑距離問題的相關(guān)操作技巧與注意事項(xiàng),需要的朋友可以參考下2018-05-05

