2015-09-06 98 views
0

在Python 2.7中,根据我如何导入模块,全局变量可能无法访问。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 

但现在,如果我做了一个丑陋的“进口*”代替,我得到follwoing:

>>> from test import * 
>>> print x 
None 
>>> f() 
>>> print x 
None 

所以变量x不再可访问..任何线索?

感谢, ÿ

+0

一个小错误:在'from test import *'后调用'f()'打印'hello' –

回答

0

from test import *会做的x = test.x相当。如果您稍后更改test.x(您致电foo()的用户将会这样做),它不会更改本地名称空间中x的副本。