1 回答

TA貢獻(xiàn)1795條經(jīng)驗 獲得超7個贊
我的第一個建議是檢查您是否可以通過使用專用TextState而不是僅分配附加屬性來簡化狀態(tài)創(chuàng)建過程。這樣,您可以使您的狀態(tài)配置更易于理解。從 yaml 或 json 文件中讀取機(jī)器配置也變得更加容易。
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)
但是您的問題是關(guān)于如何在創(chuàng)建狀態(tài)后注入標(biāo)簽功能??赡苁且驗樗枰卮蟮闹貥?gòu)和深入挖掘來改變狀態(tài)創(chuàng)建。添加state.tags = ['your', 'tags', 'here']很好,應(yīng)該可以開箱即用地創(chuàng)建圖形和標(biāo)記。要開始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...
但同樣,根據(jù)我的經(jīng)驗,當(dāng)您努力將機(jī)器配置與代碼庫的其余部分分開時,代碼變得更加易于理解和重用。在代碼中的某處修補(bǔ)狀態(tài)并分配自定義參數(shù)可能會被下一個使用您的代碼的人忽略,當(dāng)狀態(tài)在兩個調(diào)試斷點之間更改其類時肯定會令人驚訝。
添加回答
舉報