1.模塊定義:
用來從邏輯上組織Python代碼(變量、函數、類、邏輯:實現一個功能),本質就是.py結尾的python文件(文件名:test.py,對應的模塊名:test)
包定義:
用來從邏輯上組織模塊,本質就是一個目錄(必須帶有一個_int_.py文件)
2.導入方法
假設demo.py模塊中有方法test()和變量name
1)import demo
相當於將mode.py文件中的所有代碼賦值給demo這個變量
使用方法:demo.test()或者demo.name
2)import demo,demo1,demo2,demo3
同“1)”
3)from demo import * 不推薦使用
將demo.py中所有代碼引入當前文件,沒有賦值給demo!!!
使用方法:test()或者name。
錯誤示範:demo.test()和demo.name!!!
4)from demo import test,name
將demo.py中的test方法、name變量引入當前文件
使用方法:test()或者name。
5)from demo import test as test_demo
引入demo.py中的test方法,並重新命名爲:test_demo
使用方法:test_demo()
6)from . import demo
從當前路徑引入demo.py所有的代碼,並賦值給demo變量
3.import本質
導入模塊就是把引用的模塊python文件解釋一遍
import 實質就是搜索demo.py的路徑。首先搜索文件所在文件夾中的.py文件
導入包的本質就是執行該包下面的_int_.py文件
import sys,os print(sys.path) x=os.path.dirname(os.path.abspath(_file_)) sys.path.append(x) import demo.py