1 回答

TA贡献1795条经验 获得超7个赞
我的第一个建议是检查您是否可以通过使用专用TextState而不是仅分配附加属性来简化状态创建过程。这样,您可以使您的状态配置更易于理解。从 yaml 或 json 文件中读取机器配置也变得更加容易。
from transitions import Machine, State
from transitions.extensions.states import Tags
# option a) create a custom state class and use it by default
# class TextState and CustomState could be combined of course
# splitting CustomState into two classes decouples tags from the
# original state creation code
class TextState(State):
def __init__(self, *args, **kwargs):
self.text = kwargs.pop('text', '')
super(TextState, self).__init__(*args, **kwargs)
class CustomState(Tags, TextState):
pass
class CustomMachine(Machine):
state_cls = CustomState
states = []
state_initial = CustomState("initial", text="this is some text")
# we can pass tags for initialization
state_foo = dict(name="foo", text="bar!", tags=['success'])
states.append(state_initial)
states.append(state_foo)
# [...] CustomMachine(model=self, states=User.states, initial=User.initial_state)
但是您的问题是关于如何在创建状态后注入标签功能。可能是因为它需要重大的重构和深入挖掘来改变状态创建。添加state.tags = ['your', 'tags', 'here']很好,应该可以开箱即用地创建图形和标记。要开始state.is_<tag>工作,您可以更改其__class__属性:
from transitions import Machine, State
from transitions.extensions.states import Tags
# option b) patch __class__
states = []
state_initial = State("initial")
state_initial.text = "this is some text"
# we can pass tags for initialization
state_foo = State("foo")
state_foo.text = "bar!"
state_foo.tags = ['success']
states.append(state_initial)
states.append(state_foo)
# patch all states
for s in states:
s.__class__ = Tags
s.tags = []
# add tag to state_foo
states[1].tags.append('success')
class User:
states = states
initial_state = states[0]
def __init__(self):
self.machine = Machine(model=self,
states=User.states,
initial=User.initial_state)
user = User()
user.to_foo()
assert user.machine.get_state(user.state).is_success # works!
assert not user.machine.get_state(user.state).is_superhero # bummer...
但同样,根据我的经验,当您努力将机器配置与代码库的其余部分分开时,代码变得更加易于理解和重用。在代码中的某处修补状态并分配自定义参数可能会被下一个使用您的代码的人忽略,当状态在两个调试断点之间更改其类时肯定会令人惊讶。
添加回答
举报