在Python 2.7中,根据导入模块的方式,全局变量可能无法访问。
我有一个文件test.py,其中包含以下内容:
x = None
def f():
global x
x = "hello"
print x
我得到以下预期行为:
>>> import test
>>> print test.x
None
>>> test.f()
hello
>>> print test.x
hello
但是现在如果我做了一个丑陋的'import *',我会接受以下内容:
>>> from test import *
>>> print x
None
>>> f()
>>> print x
None
因此变量x不再可访问..任何线索?
感谢, ÿ
答案 0 :(得分:0)
from test import *
将相当于x = test.x
。如果您稍后更改test.x
(您对foo()
的调用将会更改),则不会更改本地命名空间中的x副本。