1. 程式人生 > 實用技巧 >殭屍程序的清除

殭屍程序的清除

更多python教程請到: 菜鳥教程 https://www.piaodoo.com/


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應用程式執行環境,本質就是一個有層次的檔案目錄結構(必須帶有一個__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"匯入包的本質就是執行該包下的__init__.py檔案,在執行檔案後,會在"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

在模組匯入的時候,預設現在當前目錄下查詢,然後再在系統中查詢。系統查詢的範圍是:sys.path下的所有路徑,按順序查詢。

4.匯入優化

  • 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

多個函式需要重複呼叫同一個模組的同一個方法,每次呼叫需要重複查詢模組。所以可以做以下優化:

  • 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"進行優化,減少了查詢的過程。

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機制的資料請關注指令碼之家其它相關文章!