python import详解

时间:2023-03-09 13:28:26
python import详解

1.import作用

引入模块

2.import的特点

一个程序中,import的模块不会重复被引用,如:

# test1.py
import test2
print test2.attr # test2.py
import test1
attr = 'hello world' # test.py
import test1

运行结果:

python import详解

结果分析:

当执行test.py时,执行import test1语句

1)判断test1是否在sys.modules中,不在,则创建一个新的module对象test1,放到sys.modules中,然后执行test1.py的其他语句,填充module test1的__dict__属性。

2)test1.py的第一句是import test2,判断test2是否在sys.modules中,不在,则创建一个新的module对象test2,放到sys.modules中,执行test2.py中的其他语句。

3)test2.py的第一句是import test1,由于test1模块在sys.modules中有了,所以会跳过这条import,执行test2.py中的其他语句,也就是"attr='hello world'",并放到了test2模块的__dict__属性。

4)接着会执行test1.py中的其他语句,即"print test2.attr",也就是"hello world"