python 全局变量不保存为全局

发布于 2025-01-04 02:57:04 字数 799 浏览 3 评论 0原文

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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

菊凝晚露 2025-01-11 02:57:04

您无需将 NexusConnectedClients 声明为全局,因为它在 run 方法中可见。当您想要(重新)绑定全局范围内的名称时,必须将变量声明为全局变量。当变量是可修改的(列表也是如此)时,只需修改它即可。

相反,您需要做的是规范对 NexusConnectedClients 的访问。您正在修改线程内的共享变量,可能不止一个。使用锁。说了这么多,我想在这么小的片段中已经没有什么可以说的了。

You don't need to declare NexusConnectedClients as global since it is visible in the run 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.

瀟灑尐姊 2025-01-11 02:57:04

解决了问题。没有从之前的测试中删除一行代码。该行重置了数组

Solved the problem. Didn't remove an line of code from previous testing. That line resetted the array

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文