是的,你的版本相当正常。 值得称道的是,它应当更多地支持国家机器,因为它在内部对不同议定书、不同事件组合等的一般模式有大约100个不同的实施。 但是,这一部分实际上并没有打上手势,它本身是:Twisted正在向网络提出反对,并将要求它采取方法(在这种情况下,stringReceived
)。 你与这一信息做些什么完全取决于您的标语和? 声明是完全合理的。
At this level, the question is not really about the "twisted way" but, rather, about better Python idioms for state machines and methods which are context-dependent. Depending on the exact needs of your protocol, your current approach may be fine, or you might want to dispatch to a method with a special name, like this:
def stringReceived(self, data):
getattr(self, "stringReceived_{}".format(self.state))(data)
def stringReceived_authenticate(self, data):
if self.auth_ok(data):
self.state = normal
else:
self.transport.loseConnection()
def stringReceived_normal(self, data):
self.do_stuff(data)
... or getting even fancier, you might want to use decorators, or metaclasses, or something else entirely. Nothing is wrong with any of these approaches.