将被import的module(即python文件) 在当前环境下执行一遍。当多次import同一个module时, python会保证只执行一次。
与import类似, 被导入的module仍然会执行且仅执行一次.区别是当以 "from *** import " 方式导入module时, python会在当前module 的命名空间中新建相应的命名。即, "from t2 import var1" 相当于: mport t2
var1= t2.var1
由于python赋值操作特性在当前代码中对"var1"的修改并不能影响到t2.py中"var1"的值. 同时, 在t2.py中对var1的修改也不能反映到当前的代码.
t1.py
from t2 import var_in_t2
import t2
print "the initial value in t1.py is %s" % var_in_t2
print "the initial value in t2.py is %s" % t2.var_in_t2
print "now try to change the value in the t1.py"
var_in_t2 = 50
print "now the value in t1.py is %s" % var_in_t2
print "now the value in t2.py is %s" % t2.var_in_t2
print "now try to change the value in the t2.py"
t2.var_in_t2 = 20
print "now the value in t1.py is %s" % var_in_t2
print "now the value in t2.py is %s" % t2.var_in_t2
t2.py
var_in_t2 = 0
def change_var():
global var_in_t2
var_in_t2 = 100
python t1.py
the initial value in t1.py is 0
the initial value in t2.py is 0
now try to change the value in the t1.py
now the value in t1.py is 50
now the value in t2.py is 0
now try to change the value in the t2.py
now the value in t1.py is 50
now the value in t2.py is 20