1, module 的实质
python 中的module 本质上就是一个相对独立的python文件.
当需要重用某些功能时, 将此功能所在的模块import到需要的模块即可.
2, import 的实质
import的过程实际上包括两个主要部分,
1) 类似于shell 的 "source" 命令, 具体说即相当于将被import的module(即python文件) 在当前环境下执行一遍.
当多次import同一个module时, python会保证只执行一次. 参考Example1
2) import的第二个部分是使被import的成员(变量名, 函数名, 类....)可见.
为保证不发生命名冲突, 需要以 module.name 的方式访问导入的成员. 参考Example2
3, from *** import 的实质 (import 与 from *** import 的区别)
与import类似, 被导入的module仍然会执行且仅执行一次.
区别是当以 "from *** import " 方式导入module时, python会在当前module 的命名空间中新建相应的命名.
即, "from t2 import var1" 相当于:
import t2
var1= t2.var1
在此过程中有一个隐含的赋值的过程
由于python赋值操作特性(参考Python 学习之1: 变量名的本质),
在当前代码中对"var1"的修改并不能影响到t2.py中"var1"的值. 同时, 在t2.py中对var1的修改也不能反映到当前的代码.
参考Example3
Example1:
t1.py:
import t2
import t3
print "execution of t1.py"
t2.py:
print "execution of t2.py"
t3.py:
import t2
print "execution of t3.py"
(env) D:\test>python t1.py
execution of t2.py
execution of t3.py
execution of t1.py
t1.py:
import t2
print "a varialbe in t2 is %s" % t2.var_in_t2
print "now will call a functiong in t2"
t2.func_in_t2
t2.py:
var_in_t2 = 0
def func_in_t2():
print "this is a function in t2.py"
print "execution of t2.py"
(env) D:\test>python t1.py
execution of t2.py
a varialbe in t2 is 0
now will call a functiong in t2
Example3:
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
(env) D:\test>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