Python中import语法和串级导入格式

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

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值