gpt4 book ai didi

Python 全局变量实例化了两次

转载 作者:行者123 更新时间:2023-12-04 10:59:47 27 4
gpt4 key购买 nike

在我的项目中,我试图在模块之​​间共享一个全局变量,如 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...
>>>

如何解决这种不良行为?

最佳答案

发生这种情况是因为您正在进行循环导入,并且因为您实际启动的代码文件发生了一些特殊情况。

如果您启动一个文件(作为 python 的参数),它将成为 __main__模块独立于其文件名。如果稍后导入相同的文件,它不会被识别为已经导入,而是以其真实名称重新导入,main在你的情况下。这就是代码运行两次的原因。第三次导入不会重新运行代码。

您可以通过阻止循环导入来修复它(不要将要导入的东西放入启动器),或者将不应运行两次的代码放入名称检查 if你已经有了。

关于Python 全局变量实例化了两次,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58892417/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com