【发布时间】:2015-10-01 22:04:02
【问题描述】:
在学习python中装饰器的概念时,我想到了是否可以使用装饰器来模拟状态机。
例子:
from enum import Enum
class CoffeeMachine(object):
def __init__(self):
self.state = CoffeeState.Initial
#@Statemachine(shouldbe, willbe)
@Statemachine(CoffeeState.Initial, CoffeeState.Grounding)
def ground_beans(self):
print("ground_beans")
@Statemachine(CoffeeState.Grounding, CoffeeState.Heating)
def heat_water(self):
print("heat_water")
@Statemachine(CoffeeState.Heating, CoffeeState.Pumping)
def pump_water(self):
print("pump_water")
class CoffeeState(Enum):
Initial = 0
Grounding = 1
Heating = 2
Pumping = 3
所以状态机所做的就是检查我当前的状态是否是请求的状态,如果是,它应该调用底层函数,最后它应该进一步设置状态。
你将如何实现它?
【问题讨论】:
-
您是否尝试过实现它?发生了什么?你在哪里卡住了?请注意,
CoffeeState必须在您尝试应用Statemachine之前 定义。
标签: python python-3.x decorator state-machine python-decorators