1.import作用
引入模塊
2.import的特點
一個程序中,import的模塊不會重復被引用,如:
# test1.py
import test2
print test2.attr
# test2.py
import test1
attr = 'hello world'
# test.py
import test1
運行結果:
結果分析:
當執行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"