最新国产好看的视频,伊人天堂AV在线,国产Aaaaaa视频,蜜臀视频在线观看一区,人妻av色图,密臀久久久精品影片,青青视频免费观看毛片,久草在线观看视,国产三级精品色情在线

Python中import機(jī)制詳解

 更新時間:2017年11月14日 08:37:12   作者:Python學(xué)習(xí)者  
在剛剛接觸python時,我們會被其優(yōu)美的格式、簡潔的語法和無窮無盡的類庫所震撼。在真正的將python應(yīng)用到實(shí)際的項(xiàng)目中,你會遇到一些無法避免的問題。最讓人困惑不解的問題有二類,一個編碼問題,另一個則是引用問題。本文主要討論關(guān)于Python中import的機(jī)制與實(shí)現(xiàn)

Python語言中import的使用很簡單,直接使用 import module_name 語句導(dǎo)入即可。這里我主要寫一下"import"的本質(zhì)。

Python官方

定義:Python code in one module gains access to the code in another module by the process of importing it.

1.定義:

模塊(module):用來從邏輯(實(shí)現(xiàn)一個功能)上組織Python代碼(變量、函數(shù)、類),本質(zhì)就是*.py文件。文件是物理上組織方式"module_name.py",模塊是邏輯上組織方式"module_name"。

包(package):定義了一個由模塊和子包組成的Python應(yīng)用程序執(zhí)行環(huán)境,本質(zhì)就是一個有層次的文件目錄結(jié)構(gòu)(必須帶有一個__init__.py文件)。

2.導(dǎo)入方法

# 導(dǎo)入一個模塊
import model_name
# 導(dǎo)入多個模塊
import module_name1,module_name2
# 導(dǎo)入模塊中的指定的屬性、方法(不加括號)、類
from moudule_name import moudule_element [as new_name]

方法使用別名時,使用"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)入模塊的時候,模塊所在文件夾會自動生成一個__pycache__\module_name.cpython-35.pyc文件。

"import module_name" 的本質(zhì)是將"module_name.py"中的全部代碼加載到內(nèi)存并賦值給與模塊同名的變量寫在當(dāng)前文件中,這個變量的類型是'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í)行文件后,會在"package_name"目錄下生成一個"__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)入的時候,默認(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

多個函數(shù)需要重復(fù)調(diào)用同一個模塊的同一個方法,每次調(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)化,減少了查找的過程。

5.模塊的分類

內(nèi)建模塊

可以通過 "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"目錄下。

第三方模塊

通過"pip install "命令安裝的模塊,以及自己在網(wǎng)站上下載的模塊。一般第三方模塊在"安裝路徑\Python\Python35\Lib\site-packages"目錄下。

相關(guān)文章

  • Pandas-DataFrame知識點(diǎn)匯總

    Pandas-DataFrame知識點(diǎn)匯總

    這篇文章主要介紹了Pandas-DataFrame知識點(diǎn)匯總,DataFrame是一種表格型數(shù)據(jù)結(jié)構(gòu),它含有一組有序的列,每列可以是不同的值,下面我們一起進(jìn)入文章了解更多詳細(xì)內(nèi)容吧,需要的小伙伴也可以參考一下
    2022-03-03
  • Python學(xué)習(xí)pygal繪制線圖代碼分享

    Python學(xué)習(xí)pygal繪制線圖代碼分享

    這篇文章主要介紹了Python學(xué)習(xí)pygal繪制線圖代碼分享,具有一定借鑒價值,需要的朋友可以參考下。
    2017-12-12
  • python排序算法之希爾排序

    python排序算法之希爾排序

    這篇文章主要介紹了python排序算法之希爾排序,希爾排序,又叫“縮小增量排序”,是對插入排序進(jìn)行優(yōu)化后產(chǎn)生的一種排序算法,需要的朋友可以參考下
    2023-04-04
  • numpy自動生成數(shù)組詳解

    numpy自動生成數(shù)組詳解

    這篇文章主要介紹了numpy自動生成數(shù)組詳解,具有一定借鑒價值,需要的朋友可以參考下。
    2017-12-12
  • Python實(shí)現(xiàn)串口通信(pyserial)過程解析

    Python實(shí)現(xiàn)串口通信(pyserial)過程解析

    這篇文章主要介紹了Python實(shí)現(xiàn)串口通信(pyserial)過程解析,文中通過示例代碼介紹的非常詳細(xì),對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價值,需要的朋友可以參考下
    2019-09-09
  • Python十類常見異常類型總結(jié)(附捕獲及異常處理方式)

    Python十類常見異常類型總結(jié)(附捕獲及異常處理方式)

    在編寫程序時難免會遇到錯誤,有的是編寫人員疏忽造成的語法錯誤,有的是程序內(nèi)部隱含邏輯問題造成的數(shù)據(jù)錯誤等等,這篇文章主要給大家介紹了關(guān)于Python十類常見異常類型總結(jié)的相關(guān)資料,文中還附捕獲及異常處理方式,需要的朋友可以參考下
    2023-06-06
  • 詳解Django配置優(yōu)化方法

    詳解Django配置優(yōu)化方法

    這篇文章主要介紹了詳解Django配置優(yōu)化方法,文中通過示例代碼介紹的非常詳細(xì),對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧
    2019-11-11
  • Python Social Auth構(gòu)建靈活而強(qiáng)大的社交登錄系統(tǒng)實(shí)例探究

    Python Social Auth構(gòu)建靈活而強(qiáng)大的社交登錄系統(tǒng)實(shí)例探究

    這篇文章主要為大家介紹了Python Social Auth構(gòu)建靈活而強(qiáng)大的社交登錄系統(tǒng)實(shí)例探究,有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進(jìn)步,早日升職加薪
    2024-01-01
  • Pandas技巧分享之讀取多個文件

    Pandas技巧分享之讀取多個文件

    日常分析數(shù)據(jù)時,只有單一數(shù)據(jù)文件的情況其實(shí)很少見,更多的情況是,從同一個數(shù)據(jù)來源定期或不定期的采集了很多數(shù)據(jù)文件,那么如何讀取多個文件呢,下面就和大家簡單講講
    2023-07-07
  • Pytorch中torch.utils.checkpoint()及用法詳解

    Pytorch中torch.utils.checkpoint()及用法詳解

    在PyTorch中,torch.utils.checkpoint?模塊提供了實(shí)現(xiàn)梯度檢查點(diǎn)(也稱為checkpointing)的功能,這篇文章給大家介紹了Pytorch中torch.utils.checkpoint()的相關(guān)知識,感興趣的朋友一起看看吧
    2024-03-03

最新評論

临漳县| 垣曲县| 晴隆县| 沭阳县| 阳曲县| 清水河县| 昭觉县| 柞水县| 东兴市| 柞水县| 瓦房店市| 瓦房店市| 南郑县| 赣州市| 沁水县| 峨边| 汝南县| 香港 | 大同市| 西充县| 鹤岗市| 昭觉县| 汽车| 怀化市| 浑源县| 鄂托克前旗| 樟树市| 东安县| 凤台县| 驻马店市| 寿宁县| 宽甸| 博兴县| 景德镇市| 连江县| 西华县| 册亨县| 安义县| 明水县| SHOW| 广丰县|