如何使用惰性初始化共享全局变量



可能是一个非常n00bish的问题,但每次都会让我。。。

有人能向我解释一下为什么下面印的是"无"吗?

test1.py

test = None
def init():
global test
test = 1

test2.py

from test1 import test, init
# test1.test should be getting a value here
init()
# I expect test to be a reference to test1.test 
# but behaves like a copy on import-time ?!
print(test)

通过执行test = 1,您正在更改test的引用,但上一个引用(到None(已在test2.py中导入。如果你想保留它,你可以,例如,使用一个对象:

# test1.py
test = {}
def init():
# you do not need `global` since you are not rewriting the variable
test['x'] = 1
# test2.py
from test1 import init, test
assert test == {}
init()
assert test['x'] == 1  # works

使用from test1 import test时,您将在本地作用域中创建一个绑定到test1.test值的变量。将值分配给test将用新值替换它,但原始test1.test将保持不变。因此,在您的情况下,当您在test2.py中调用init()时,它实际上会使用test1.test变量,而不是本地作用域中的变量。

>>> import test1
>>> from test1 import test, init
>>> init()
>>> print(test)
None
>>> print(test1.test)
1

请注意,正如michaeldel在他的回复中所写的那样,当您使用可变数据类型(如list或dict(时,情况会有所不同,因为修改它确实会影响原始变量。我的答案是基于ThiefMaster对类似问题的回答。你可以查看它以获得更详细的解释。

最新更新