python 全局变量不保存为全局
NexusConnectedClients = []
class Thread1(NexusCore.Thread):
def Run():
global NexusConnectedClients
if(IncomingCommand == "ADDCLIENT"):
NewClientOBJ = [
LastCID,
ClientType,
ClientADDR,
ClientObject,
Args[1],
Args[2],
'{"events":[]}'
]
NexusConnectedClients.append(NewClientOBJ)
elif(IncomingCommand == "LISTCLIENTS"):
SendResponse(NexusConnectedClients)
当我添加客户端时,就可以了。当我读取 NexusConnectedClients 变量时,它被添加到列表中。 但是当我运行 LISTCLIENTS 函数时,列表为空。怎么了?
我稍微简化了代码。所有变量都已设置,并且所有其他全局变量都按其应有的方式工作。
编辑 我发现了错误,这段代码没有任何问题,但另一个函数从 NexusConnectedClients 数组中删除了该元素
NexusConnectedClients = []
class Thread1(NexusCore.Thread):
def Run():
global NexusConnectedClients
if(IncomingCommand == "ADDCLIENT"):
NewClientOBJ = [
LastCID,
ClientType,
ClientADDR,
ClientObject,
Args[1],
Args[2],
'{"events":[]}'
]
NexusConnectedClients.append(NewClientOBJ)
elif(IncomingCommand == "LISTCLIENTS"):
SendResponse(NexusConnectedClients)
When i add an client, it is ok. When i read the NexusConnectedClients
variable, it is add to the list.
But when i run the LISTCLIENTS function, the list is empty. What is wrong?
I Simplified the code a bit. all the variables are set and all other global variables work as they should.
EDIT
I found the mistake, nothing wrong with this code but another function deleted the element from the NexusConnectedClients
array
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
您无需将 NexusConnectedClients 声明为全局,因为它在
run
方法中可见。当您想要(重新)绑定全局范围内的名称时,必须将变量声明为全局变量。当变量是可修改的(列表也是如此)时,只需修改它即可。相反,您需要做的是规范对 NexusConnectedClients 的访问。您正在修改线程内的共享变量,可能不止一个。使用锁。说了这么多,我想在这么小的片段中已经没有什么可以说的了。
You don't need to declare
NexusConnectedClients
as global since it is visible in therun
method. A variable must be declared global when you want to (re)bind a name in the global scope. When a variable is modifiable, and lists are, just modify it.Instead what you have to do is to regulate the access to the
NexusConnectedClients
. You are modifying a shared variable inside a thread, maybe more than one. Use a lock. Said that, I think nothing more could be said in a such small snippet.解决了问题。没有从之前的测试中删除一行代码。该行重置了数组
Solved the problem. Didn't remove an line of code from previous testing. That line resetted the array