我想用python autobahn创建一个聊天应用程序,将收到的消息发送给所有客户端。因此,首先我必须定义一个全局变量,比如字典,并在上面添加一些信息(客户端:消息尚未下载)。我需要定义一个全局变量,但我做不到我像这样定义字典,但它对每个客户端都是唯一的
class MyProtocol(WebSocketServerProtocol):
clients_msgs = {} # this must be global for all clients
.
.
.
那么我应该如何定义我的变量呢?
对于类的所有实例之间的全局变量,必须在python中使用ClassName.attributeName。
>>> class Test(object):
... i = 3
...
>>> Test.i
3
>>> t = Test()
>>> t.i # static variable accessed via instance
3
>>> t.i = 5 # but if we assign to the instance ...
>>> Test.i # we have not changed the static variable
3
>>> t.i # we have overwritten Test.i on t by creating a new attribute t.i
5
>>> Test.i = 6 # to change the static variable we do it by assigning to the class
>>> t.i
5
>>> Test.i
6
>>> u = Test()
>>> u.i
6