Python 2.7:全局导入模块

Python 2.7 : global with imported modules

在 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.. 有什么线索吗?

谢谢, 是

from test import * 相当于 x = test.x。如果您稍后更改 test.x(您对 foo() 的调用将执行此操作),它不会更改本地命名空间中 x 的副本。