链接
没想到不少人能摸到我的博客地址,哈哈哈,引了一波。
Github仓库:https://github.com/kifuan/helang
状态机
我自己写了一个绑定枚举值和方法的小工具,挺好玩的。源码很短,就下面这几行:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15
| 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)
|
之后用的时候可以这样用:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28
| 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') self._end = True
foo = Foo() foo.start()
|
运行结果: