Python全局变量实例化twi

2024-04-24 08:04:43 发布

您现在位置:Python中文网/ 问答频道 /正文

在我的项目中,我尝试在模块间共享一个全局变量,如Python文档中所述:https://docs.python.org/3/faq/programming.html#how-do-i-share-global-variables-across-modules

然而,我似乎发现全局变量被实例化了两次,我不知道为什么。我希望变量是一个单例。你知道吗

我用这个最小的例子再现了这个问题:

# main.py
class TheClass:
    def __init__(self):
        print("init TheClass")

    def do_work(self):
        import worker
        worker.do_work()

the_class:TheClass = TheClass()

if __name__ == '__main__':
    the_class.do_work()
# worker.py
from main import the_class

def do_work():
    print("doing work...")

python main.py的输出:

init TheClass
init TheClass
doing work...

“init TheClass”记录了两次,这意味着类被实例化了两次。你知道吗

我无法在交互式Python shell中重现这种行为:

Python 3.7.4 (tags/v3.7.4:e09359112e, Jul  8 2019, 20:34:20) [MSC v.1916 64 bit (AMD64)] on win32
Type "help", "copyright", "credits" or "license" for more information.
>>> import main
init TheClass
>>> main.the_class.do_work()
doing work...
>>>

我该如何纠正这种不受欢迎的行为?你知道吗


Tags: the实例pyimportselfinitmaindef
1条回答
网友
1楼 · 发布于 2024-04-24 08:04:43

这是因为您有一个循环导入,并且由于实际启动的代码文件发生了一些特殊的情况。你知道吗

如果启动一个文件(作为python的参数),它将成为独立于文件名的__main__模块。如果在以后的某个时间点导入了同一个文件,则不会将其识别为已导入并以其真实名称重新导入,在本例中为main。这就是代码运行两次的原因。导入的第三个将不会重新运行代码。你知道吗

您可以通过阻止循环导入(不要将要导入的内容放入starter)或将不应运行两次的代码放入已存在的名称检查if来修复它。你知道吗

相关问题 更多 >