问题描述
class Video:
## Define the states
PLAYING = "playing"
PAUSED = "paused"
STOPPED = "stopped"
def __init__(self,source):
self.source = source
transitions = [
{"trigger":"play","source":self.PAUSED,"dest":self.PLAYING},{"trigger":"play","source":self.STOPPED,##
{"trigger":"pause","dest":self.PAUSED},##
{"trigger":"stop","dest":self.STOPPED},{"trigger":"stop","source":self.PLAYING,"dest":self.STOPPED}
]
self.machine = Machine(
model = self,transitions = transitions,initial = self.STOPPED)
def pause(self):
print ("pause")
def play(self):
print ("play")
def stop(self):
print ("stop")
但是我称之为一个,它不起作用:
test = Video("some text")
返回警告:
2020-09-27 17:25:50,255 [11472] WARNING transitions.core:828: [JupyterRequire] Model already contains an attribute 'play'. Skip binding.
2020-09-27 17:25:50,259 [11472] WARNING transitions.core:828: [JupyterRequire] Model already contains an attribute 'pause'. Skip binding.
2020-09-27 17:25:50,260 [11472] WARNING transitions.core:828: [JupyterRequire] Model already contains an attribute 'stop'. Skip binding.
但是主要问题是状态不会改变:
这是原始演讲的代码:
解决方法
我将修改后的代码发布到此处,从而为您提供预期的输出。对代码格式表示歉意,我真的在这里使用标记编辑器。
有问题的代码似乎缺少的东西
-
您没有将状态列表传递给FSM计算机。
-
此外,机器看起来还具有触发功能。您具有相同的命名函数似乎会覆盖那些[1]。我认为触发任何功能的正确方法是使用“ after”属性和功能名称。
from transitions import Machine class Video: ## Define the states PLAYING = "playing" PAUSED = "paused" STOPPED = "stopped" states = [PLAYING,PAUSED,STOPPED] def __init__(self,source): self.source = source transitions = [ {"trigger":"play","source":self.PAUSED,"dest":self.PLAYING,"after": "log_play"},{"trigger":"play","source":self.STOPPED,## {"trigger":"pause","dest":self.PAUSED},## {"trigger":"stop","dest":self.STOPPED},{"trigger":"stop","source":self.PLAYING,"dest":self.STOPPED} ] self.machine = Machine( model = self,transitions = transitions,states = self.states,initial = self.STOPPED) def log_pause(self): print ("pause") def log_play(self): print ("play") def log_stop(self): print ("stop")
参考: