pyton中类的变量与对象的变量误用
昨天在开发tornado服务器时碰到一个奇怪的错误,
客户端第一次连接没问题,第二次就报下面:
RuntimeError: Cannot write() after finish(). May be
caused by using async operations without
the @asynchronous decorator。
报错位置是在执行
self.handler.write(cmdca.SerializeToString())的时候。
从错误日志可以知道是因为连接完成,断开造成的。但
不知道为什么,开始还以为是tornado的超时断开机制。
后来慢慢分析,注释掉部分代码,就可以了,所以猜测
是那些被注释的代码有问题。于是就看那些代码,看着看着
发现了Invoker类
class Invoker(): commandList = [] def setOption(self,command): print('##setoption.') self.commandList.append(command) def cancelOption(self,command): print('##canceloption.') self.commandList.remove(command) def notify(self): print('##:notify.') #command = self.commandList[0] for command in self.commandList: command.execute()
里一个奇怪的变量commandList.它属于类
每次连接都会将处理器添加到这个commandList中,但是当
连接断开时,却没有删除加到commandList中的处理器,所以
就出现上面的问题,解决办法也自然而得了。