若是把 python 比做手機,pip
就是手機的應用商店,模塊就是 手機裏的 App 。python
在Python中,總共有如下四種形式的模塊:函數
xxx.py
文件pip
安裝的模塊(應用商店下載的 App )\_\_init\_\_.py
文件,該文件夾稱之爲包)import 模塊名
import time # 導入 time 模塊 time.sleep(1) # 延時 1s
import 模塊名
首次導入過程當中發生的三件事:code
time.py
中的全部代碼讀入名稱空間,而後運行time.方法名
使用time模塊中的方法from 模塊名 import 具體的功能
from time import sleep sleep(1)
from 模塊名 import 具體的功能
首次導入過程當中發生的三件事:ip
time.py
中的全部代碼讀入名稱空間,而後運行sleep()
模塊名import
須要加前綴;from...import...
不須要加前綴from...import...
容易與當前執行文件中名稱空間中的名字衝突理解核心:內存
導入文件時發生的三件事:作用域
假設有兩個文件 file1.py 和 file2.py :pycharm
# file1.py from file2 import y x = 'from file2' print(y)
# file2.py from file1 import x y = 'from file2' print(x)
對於以上兩個文件:it
若是運行 file1,運行結果:pip
ImportError: cannot import name 'y' from 'file2'
若是運行 file2,運行結果:class
ImportError: cannot import name 'x' from 'file1'
這種問題就是因爲循環導入引發的。
# file1.py x = 'from file2' from file2 import y print(y)
# file2.py y = 'from file2' from file1 import x print(x)
對於以上兩個文件:
若是運行 file1,運行結果:
from file2 from file1 from file2
若是運行 file2,運行結果:
from file1 from file2 from file1
雖然解決了錯誤,可是獲得了三個結果,顯然不是咱們想要的內容。
利用函數定義階段只識別語法,不執行代碼的特性,將代碼寫進函數裏面
def file1(): from file2 import y print(y) x = 'from file1' # file1()
def file2(): from file1 import x print(x) y = 'from file2' # file2()
對於以上兩個文件:
若是運行 file1(須要調用f1)運行結果:
from file2
若是運行 file2(須要調用f2)運行結果:
from file1
這種方法能夠解決循環導入的問題,且達到了預期的輸出。
最好的解決方法是不要出現循環導入。
導入模塊時查找模塊的順序是:
sys.path
中找print(sys.path)
打印結果:
# # 導入模塊的時候,解釋器會按照列表的順序搜索,直到找到第一個模塊 ['(當前執行文件本身保存的位置)相對路徑下的當前目錄', '當前執行文件的根目錄', 'D:\\Program Files\\JetBrains\\PyCharm 2019.2.2\\helpers\\pycharm_display', 'D:\\Program Files\\Python\\Python37\\python37.zip', 'D:\\Program Files\\Python\\Python37\\DLLs', 'D:\\Program Files\\Python\\Python37\\lib', 'D:\\Program Files\\Python\\Python37', 'D:\\Program Files\\Python\\Python37\\lib\\site-packages', 'D:\\Program Files\\JetBrains\\PyCharm 2019.2.2\\helpers\\pycharm_matplotlib_backend']
當前正在運行的文件
當 file1 導入 file2 ,運行file1 時,file2 就是模塊文件
當 file2 導入 file1 ,運行file2 時,file1 就是模塊文件
__name__
__name__
是每一個文件獨有的,當該文件做爲執行文件運行時, __name__
等於'main';當該文件做爲模塊文件導入時, __name__
等於文件名。