欧美bbbwbbbw肥妇,免费乱码人妻系列日韩,一级黄片

詳解Python中import機制

 更新時間:2020年09月11日 09:00:14   作者:Python學習者  
這篇文章主要介紹了Python中import機制的相關資料,幫助大家更好的理解和學習python,感興趣的朋友可以了解下

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

Python官方定義:

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

1.定義:

  • 模塊(module):用來從邏輯(實現一個功能)上組織Python代碼(變量、函數、類),本質就是*.py文件。文件是物理上組織方式"module_name.py",模塊是邏輯上組織方式"module_name"。
  • 包(package):定義了一個由模塊和子包組成的Python應用程序執(zhí)行環(huán)境,本質就是一個有層次的文件目錄結構(必須帶有一個__init__.py文件)。

2.導入方法

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

方法使用別名時,使用"new_name()"調用函數,文件中可以再定義"module_element()"函數。

3.import本質(路徑搜索和搜索路徑)

  • 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)

運行結果:

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'>

在導入模塊的時候,模塊所在文件夾會自動生成一個__pycache__\module_name.cpython-35.pyc文件。

"import module_name" 的本質是將"module_name.py"中的全部代碼加載到內存并賦值給與模塊同名的變量寫在當前文件中,這個變量的類型是'module';<module 'module_name' from 'E:\\PythonImport\\module_name.py'>

  • module_test02.py
# -*- coding:utf-8 -*-
from module_name import name

print(name)

運行結果;

E:\PythonImport>python module_test02.py
This is module_name.py
Hello

"from module_name import name" 的本質是導入指定的變量或方法到當前文件中。

  • 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")

運行結果:

E:\PythonImport>python module_test03.py
This is package_name.__init__.py
This is module_test03.py

"import package_name"導入包的本質就是執(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文件導入"package_name"中的"hello"模塊
from . import hello
print("This is package_name.__init__.py")

運行結果:

E:\PythonImport>python module_test03.py
Hello World
This is package_name.__init__.py
This is module_test03.py

在模塊導入的時候,默認現在當前目錄下查找,然后再在系統(tǒng)中查找。系統(tǒng)查找的范圍是:sys.path下的所有路徑,按順序查找。

4.導入優(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()

運行結果:

E:\PythonImport>python module_test04.py
This is module_name.py
Hello
fun a
Hello
fun b

多個函數需要重復調用同一個模塊的同一個方法,每次調用需要重復查找模塊。所以可以做以下優(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()

運行結果:

E:\PythonImport>python module_test04.py
This is module_name.py
Hello
fun a
Hello
fun b

可以使用"from module_name import hello"進行優(yōu)化,減少了查找的過程。

5.模塊的分類

內建模塊

可以通過 "dir(__builtins__)" 查看Python中的內建函數

>>> 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']

非內建函數需要使用"import"導入。Python中的模塊文件在"安裝路徑\Python\Python35\Lib"目錄下。

第三方模塊

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

以上就是詳解Python中import機制的詳細內容,更多關于Python import機制的資料請關注腳本之家其它相關文章!

相關文章

  • python 中的divmod數字處理函數淺析

    python 中的divmod數字處理函數淺析

    這篇文章主要介紹了python divmod數字處理函數的相關資料,感興趣的朋友一起看看吧
    2017-10-10
  • Python 實現自動導入缺失的庫

    Python 實現自動導入缺失的庫

    這篇文章主要介紹了Python 實現自動導入缺失的庫,解決導入 Python 庫失敗的問題,本文分三種情況給大家介紹,需要的朋友可以參考下
    2019-10-10
  • Python獲取文件所在目錄和文件名的方法

    Python獲取文件所在目錄和文件名的方法

    下面小編就為大家?guī)硪黄狿ython獲取文件所在目錄和文件名的方法。小編覺得挺不錯的,現在就分享給大家,也給大家做個參考。一起跟隨小編過來看看吧
    2017-01-01
  • 通過Jython調用Python腳本的實現方法

    通過Jython調用Python腳本的實現方法

    Jython 是 Python 的純 Java 實現。她無縫地結合了 Java 類與 Python,使用戶能以 Python 語言的語法編寫在 Java 虛擬機上運行的 軟件,本文重點給大家介紹通過Jython調用Python腳本的實現方法,一起看看吧
    2021-06-06
  • Python基于mediainfo批量重命名圖片文件

    Python基于mediainfo批量重命名圖片文件

    這篇文章主要介紹了Python基于mediainfo批量重命名圖片文件的方法,幫助大家更好的理解和使用python,感興趣的朋友可以了解下
    2020-12-12
  • Python錯誤處理操作示例

    Python錯誤處理操作示例

    這篇文章主要介紹了Python錯誤處理操作,結合實例形式分析了Python使用try...except...finaly語句進行錯誤處理的相關操作技巧與注意事項,需要的朋友可以參考下
    2018-07-07
  • python3爬蟲獲取html內容及各屬性值的方法

    python3爬蟲獲取html內容及各屬性值的方法

    今天小編就為大家分享一篇python3爬蟲獲取html內容及各屬性值的方法,具有很好的參考價值,希望對大家有所幫助。一起跟隨小編過來看看吧
    2018-12-12
  • 基于Python數據分析之pandas統(tǒng)計分析

    基于Python數據分析之pandas統(tǒng)計分析

    這篇文章主要介紹了基于Python數據分析之pandas統(tǒng)計分析,具有很好對參考價值,希望對大家有所幫助。一起跟隨小編過來看看吧
    2020-03-03
  • Python使用OPENCV的目標跟蹤算法實現自動視頻標注效果

    Python使用OPENCV的目標跟蹤算法實現自動視頻標注效果

    這篇文章主要介紹了Python使用OPENCV的目標跟蹤算法進行簡單的自動視頻標注,本文通過實例代碼給大家介紹的非常詳細,對大家的學習或工作具有一定的參考借鑒價值,需要的朋友可以參考下
    2021-09-09
  • 樹莓派使用python-librtmp實現rtmp推流h264的方法

    樹莓派使用python-librtmp實現rtmp推流h264的方法

    今天小編就為大家分享一篇樹莓派使用python-librtmp實現rtmp推流h264的方法,具有很好的參考價值,希望對大家有所幫助。一起跟隨小編過來看看吧
    2019-07-07

最新評論