使用python在高速公路中定义全局变量

时间:2015-02-23 16:09:52

标签: python web-services global-variables autobahn

我想用python autobahn创建一个聊天应用程序,将收到的消息发送给所有客户端。首先,我必须定义一个全局变量,如字典,并在其上放置一些信息(客户端:消息尚未下载)。 我需要定义一个全局变量,但我不能这样做 我像这个代码一样定义了这个字典,但它对每个客户端都是唯一的

class MyProtocol(WebSocketServerProtocol):
    clients_msgs = {}  # this must be global for all clients
    .
    .
    .

那么我应该如何定义我的变量呢?

1 个答案:

答案 0 :(得分:0)

  

您必须在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