2015-09-06 96 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的副本。