链接
没想到不少人能摸到我的博客地址,哈哈哈,引了一波。
Github仓库:https://github.com/kifuan/helang
状态机
我自己写了一个绑定枚举值和方法的小工具,挺好玩的。源码很短,就下面这几行:
from enum import Enum
class Methods:
def __init__(self):
self._methods = dict()
def bind(self, enum: Enum):
def bind_method(method: callable):
self._methods[enum] = method
return method
return bind_method
def apply(self, enum: Enum, *args, **kwargs):
return self._methods[enum](*args, **kwargs)
之后用的时候可以这样用:
methods = Methods()
class State(Enum):
A = 1
B = 2
class Foo:
def __init__(self):
self._state = State.A
self._end = False
def start(self):
while not self._end:
methods.apply(self._state, self)
@methods.bind(State.A)
def _state_a(self):
print('State A')
self._state = State.B
@methods.bind(State.B)
def _state_b(self):
print('State B')
# End of running.
self._end = True
foo = Foo()
foo.start()
运行结果:
State A
State B