繁体   English   中英

Python class 跨线程变量使用具有不同的值

[英]Python class variable usage across thread have different value

我对通过多线程访问 class 变量感到困惑。 我在一个 django 应用程序中,我在服务器启动时初始化一个 class 以注入一些配置。 然后根据用户请求,我在该 class 上调用了一些方法,但配置为无。

class SharedService:
    _queue_name = None

    @staticmethod
    def config(queue_name=None):
        if queue_name:
            SharedService._queue_name = queue_name
        print(SharedService._queue_name)    # this print the "alert"

    @staticmethod
    def send_message(data):
        print(SharedService._queue_name)    # this print None should print "alert"

如果在启动时加载的 django 设置 class 有用,我会这样做:

SharedService.config(queue_name="alert")

在我刚刚调用的用户端点中:

SharedService.send_message("blabla")

我确定它以前确实有效,但我们最近确实更新到 python 3.10 和 django 3.2 并且可能相关(或不相关!)

好的,这完全来自外场!

共享服务来自外部库,实际上可以从两个路径导入,因为我们的 python 路径中存在错误。

在设置文件中,我正在做

from lib.services import SharedService

并从请求处理代码

from services import SharedService

这显然创建了两个不同的 class 定义,因此,第二个用法没有初始化。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM