Python中import機(jī)制詳解
Python語(yǔ)言中import的使用很簡(jiǎn)單,直接使用 import module_name 語(yǔ)句導(dǎo)入即可。這里我主要寫(xiě)一下"import"的本質(zhì)。
Python官方
定義:Python code in one module gains access to the code in another module by the process of importing it.
1.定義:
模塊(module):用來(lái)從邏輯(實(shí)現(xiàn)一個(gè)功能)上組織Python代碼(變量、函數(shù)、類(lèi)),本質(zhì)就是*.py文件。文件是物理上組織方式"module_name.py",模塊是邏輯上組織方式"module_name"。
包(package):定義了一個(gè)由模塊和子包組成的Python應(yīng)用程序執(zhí)行環(huán)境,本質(zhì)就是一個(gè)有層次的文件目錄結(jié)構(gòu)(必須帶有一個(gè)__init__.py文件)。
2.導(dǎo)入方法
# 導(dǎo)入一個(gè)模塊 import model_name # 導(dǎo)入多個(gè)模塊 import module_name1,module_name2 # 導(dǎo)入模塊中的指定的屬性、方法(不加括號(hào))、類(lèi) from moudule_name import moudule_element [as new_name]
方法使用別名時(shí),使用"new_name()"調(diào)用函數(shù),文件中可以再定義"module_element()"函數(shù)。
3.import本質(zhì)(路徑搜索和搜索路徑)
moudel_name.py
# -*- coding:utf-8 -*-
print("This is module_name.py")
name = 'Hello'
def hello():
print("Hello")
module_test01.py
# -*- coding:utf-8 -*-
import module_name
print("This is module_test01.py")
print(type(module_name))
print(module_name)
運(yùn)行結(jié)果:
E:\PythonImport>python module_test01.py This is module_name.py This is module_test01.py <class 'module'> <module 'module_name' from 'E:\\PythonImport\\module_name.py'>
在導(dǎo)入模塊的時(shí)候,模塊所在文件夾會(huì)自動(dòng)生成一個(gè)__pycache__\module_name.cpython-35.pyc文件。
"import module_name" 的本質(zhì)是將"module_name.py"中的全部代碼加載到內(nèi)存并賦值給與模塊同名的變量寫(xiě)在當(dāng)前文件中,這個(gè)變量的類(lèi)型是'module';<module 'module_name' from 'E:\\PythonImport\\module_name.py'>
module_test02.py
# -*- coding:utf-8 -*- from module_name import name print(name)
運(yùn)行結(jié)果;
E:\PythonImport>python module_test02.py
This is module_name.py
Hello
"from module_name import name" 的本質(zhì)是導(dǎo)入指定的變量或方法到當(dāng)前文件中。
package_name / __init__.py
# -*- coding:utf-8 -*-
print("This is package_name.__init__.py")
module_test03.py
# -*- coding:utf-8 -*-
import package_name
print("This is module_test03.py")
運(yùn)行結(jié)果:
E:\PythonImport>python module_test03.py This is package_name.__init__.py This is module_test03.py
"import package_name"導(dǎo)入包的本質(zhì)就是執(zhí)行該包下的__init__.py文件,在執(zhí)行文件后,會(huì)在"package_name"目錄下生成一個(gè)"__pycache__ / __init__.cpython-35.pyc" 文件。
package_name / hello.py
# -*- coding:utf-8 -*-
print("Hello World")
package_name / __init__.py
# -*- coding:utf-8 -*-
# __init__.py文件導(dǎo)入"package_name"中的"hello"模塊
from . import hello
print("This is package_name.__init__.py")
運(yùn)行結(jié)果:
E:\PythonImport>python module_test03.py Hello World This is package_name.__init__.py This is module_test03.py
在模塊導(dǎo)入的時(shí)候,默認(rèn)現(xiàn)在當(dāng)前目錄下查找,然后再在系統(tǒng)中查找。系統(tǒng)查找的范圍是:sys.path下的所有路徑,按順序查找。
4.導(dǎo)入優(yōu)化
module_test04.py
# -*- coding:utf-8 -*-
import module_name
def a():
module_name.hello()
print("fun a")
def b():
module_name.hello()
print("fun b")
a()
b()
運(yùn)行結(jié)果:
E:\PythonImport>python module_test04.py This is module_name.py Hello fun a Hello fun b
多個(gè)函數(shù)需要重復(fù)調(diào)用同一個(gè)模塊的同一個(gè)方法,每次調(diào)用需要重復(fù)查找模塊。所以可以做以下優(yōu)化:
module_test05.py
# -*- coding:utf-8 -*-
from module_name import hello
def a():
hello()
print("fun a")
def b():
hello()
print("fun b")
a()
b()
運(yùn)行結(jié)果:
E:\PythonImport>python module_test04.py This is module_name.py Hello fun a Hello fun b
可以使用"from module_name import hello"進(jìn)行優(yōu)化,減少了查找的過(guò)程。
5.模塊的分類(lèi)
內(nèi)建模塊
可以通過(guò) "dir(__builtins__)" 查看Python中的內(nèi)建函數(shù)
>>> dir(__builtins__)
['ArithmeticError', 'AssertionError', 'AttributeError', 'BaseException', 'BlockingIOError', 'BrokenPipeError', 'BufferError', 'BytesWarning', 'ChildProcessError', 'ConnectionAbortedError', 'ConnectionError', 'ConnectionRefusedError', 'ConnectionResetError', 'DeprecationWarning', 'EOFError', 'Ellipsis', 'EnvironmentError', 'Exception', 'False', 'FileExistsError', 'FileNotFoundError', 'FloatingPointError', 'FutureWarning', 'GeneratorExit', 'IOError', 'ImportError', 'ImportWarning', 'IndentationError', 'IndexError', 'InterruptedError', 'IsADirectoryError', 'KeyError', 'KeyboardInterrupt', 'LookupError', 'MemoryError', 'NameError', 'None', 'NotADirectoryError', 'NotImplemented', 'NotImplementedError', 'OSError', 'OverflowError', 'PendingDeprecationWarning', 'PermissionError', 'ProcessLookupError', 'RecursionError', 'ReferenceError', 'ResourceWarning', 'RuntimeError', 'RuntimeWarning', 'StopAsyncIteration', 'StopIteration', 'SyntaxError', 'SyntaxWarning', 'SystemError', 'SystemExit', 'TabError', 'TimeoutError', 'True', 'TypeError', 'UnboundLocalError', 'UnicodeDecodeError', 'UnicodeEncodeError', 'UnicodeError', 'UnicodeTranslateError', 'UnicodeWarning', 'UserWarning', 'ValueError', 'Warning', 'WindowsError', 'ZeroDivisionError', '_', '__build_class__', '__debug__', '__doc__', '__import__', '__loader__','__name__', '__package__', '__spec__', 'abs', 'all', 'any', 'ascii', 'bin', 'bool', 'bytearray', 'bytes', 'callable', 'chr', 'classmethod', 'compile', 'complex', 'copyright', 'credits', 'delattr', 'dict', 'dir', 'divmod', 'enumerate', 'eval', 'exec', 'exit', 'filter', 'float', 'format', 'frozenset', 'getattr', 'globals', 'hasattr', 'hash', 'help', 'hex', 'id', 'input', 'int', 'isinstance', 'issubclass', 'iter', 'len', 'license', 'list', 'locals', 'map', 'max', 'memoryview', 'min', 'next', 'object', 'oct', 'open', 'ord', 'pow', 'print', 'property', 'quit', 'range', 'repr', 'reversed', 'round','set', 'setattr', 'slice', 'sorted', 'staticmethod', 'str', 'sum', 'super', 'tuple', 'type', 'vars', 'zip']
非內(nèi)建函數(shù)需要使用"import"導(dǎo)入。Python中的模塊文件在"安裝路徑\Python\Python35\Lib"目錄下。
第三方模塊
通過(guò)"pip install "命令安裝的模塊,以及自己在網(wǎng)站上下載的模塊。一般第三方模塊在"安裝路徑\Python\Python35\Lib\site-packages"目錄下。
相關(guān)文章
web自動(dòng)化測(cè)試Selenium點(diǎn)擊元素的常用方法
在Web自動(dòng)化測(cè)試中,Selenium提供多種點(diǎn)擊方法,常用的click()方法通過(guò)選中元素并觸發(fā)點(diǎn)擊事件,若click()方法不穩(wěn)定,可以采用JavaScript執(zhí)行點(diǎn)擊或使用ActionChains類(lèi)模擬鼠標(biāo)點(diǎn)擊,需要的朋友可以參考下2024-09-09
解決python打開(kāi)https出現(xiàn)certificate verify failed的問(wèn)題
這篇文章主要介紹了解決python打開(kāi)https出現(xiàn)certificate verify failed的問(wèn)題,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。一起跟隨小編過(guò)來(lái)看看吧2020-09-09
Python構(gòu)造自定義方法來(lái)美化字典結(jié)構(gòu)輸出的示例
這篇文章主要介紹了用Python構(gòu)造自定義方法來(lái)美化字典結(jié)構(gòu)輸出的示例,原理就是利用遞歸法來(lái)拼接字符串,需要的朋友可以參考下2016-06-06
使用pyQT5顯示網(wǎng)頁(yè)的實(shí)現(xiàn)步驟
本文主要介紹了使用pyQT5顯示網(wǎng)頁(yè)的實(shí)現(xiàn)步驟,文中通過(guò)示例代碼介紹的非常詳細(xì),具有一定的參考價(jià)值,感興趣的小伙伴們可以參考一下2021-10-10
pytorch深度神經(jīng)網(wǎng)絡(luò)入門(mén)準(zhǔn)備自己的圖片數(shù)據(jù)
這篇文章主要為大家介紹了pytorch深度神經(jīng)網(wǎng)絡(luò)入門(mén)準(zhǔn)備自己的圖片數(shù)據(jù)示例過(guò)程,有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進(jìn)步,早日升職加薪2022-06-06
Python 整行讀取文本方法并去掉readlines換行\(zhòng)n操作
這篇文章主要介紹了Python 整行讀取文本方法并去掉readlines換行\(zhòng)n操作,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。一起跟隨小編過(guò)來(lái)看看吧2020-09-09
python不到50行代碼完成了多張excel合并的實(shí)現(xiàn)示例
這篇文章主要介紹了python不到50行代碼完成了多張excel合并的實(shí)現(xiàn)示例,文中通過(guò)示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面隨著小編來(lái)一起學(xué)習(xí)學(xué)習(xí)吧2020-05-05

