import语法
python中的import有3种格式:
1import module
2:from module import fun1,fun2,var1,var2
2:from module import *
其中module是模块module.py的名字,fun1,fun2,var1,var2是定义在module中的函数和变量。使用第1种方式,调用函数或变量时要用module.fun1(),module.var1这种格式,即间接导入。使用第2、3种方式,调用函数或变量要用fun1(),var1这种格式,即不加前缀,直接导入。第2种方式只能使用被导入的那些函数和变量,第3种方式是把module中的所有变量、函数都导入。
不管哪种import,都会在导入时自动执行被导入模块中的独立代码(函数之外的代码,比如print()),但若要使用被导入模块中定义的变量,还要以import的格式为准。也可以使用exec(open('module.py').read()),相当于把module.py中的代码原封不动插入到exec这一行。
串级导入
假设var1和var2分别是在test1和test2中定义的变量,现打算在main中调用var2,因此需要在main中导入test1,在test1中导入test2。每次导入都有3种import方式,则有9种不同的组合,测试结果:
1.在main.py中:import test1,在test1.py中:import test2 调用格式:test1.test2.var2
2.在main.py中:import test1,在test1.py中:from test2 import var2 调用格式:test1.var2
3.在main.py中:import test1,在test1.py中:from test2 import * 调用格式:test1.var2
4.在main.py中:from test1 import test2.var2,在test1.py中:import test2 语法错误
5.在main.py中:from test1 import var2,在test1.py中:from test2 import var2 调用格式:var2
6.在main.py中:from test1 import var2,在test1.py中:from test2 import * 调用格式:var2
7.在main.py中:from test1 import *,在test1.py中:import test2 调用格式:test2.var2
8.在main.py中:from test1 import *,在test1.py中:from test2 import var2 调用格式:var2
9.在main.py中:from test1 import *,在test1.py中:from test2 import * 调用格式:var2