Python 模組

Python 模組本質上是一個 Python 腳本文件,可以包含變數、函數和類。Python 模組幫助我們組織代碼,然後在其他類或 Python 腳本中引用它們。

Python 模組

A file containing Python definitions and statements is called a python module. So naturally, the file name is the module name which is appended with the suffix .py. For better understanding let’s create a python module to explore it completely. First create a file named printNumbers.py with the following contents.

def printForward(n):

    #print 1 to n
    for i in range(n):
        print(i+1)


def printBackwards(n):

    #print n to 1
    for i in range(n):
        print(n-i)

現在在 Python 解譯器中使用以下命令導入此模組:

import printNumbers

這個導入命令將在當前目錄和 PATH 變量位置中查找 printNumbers.py 文件。一旦找到文件,文件中的代碼將可供我們使用。現在要訪問模組的函數,我們需要使用模組名稱,如下所示:有時如果模組很大,為了方便調用函數,我們可以像下面這樣重命名導入:

導入 Python 模組的特定函數

有時候導入 Python 模組的所有函數並不是必要的。我們可能只需要其中一兩個函數。在這種情況下,我們可以使用以下變體的導入語句; 這裡需要注意的一件事是,當我們導入 printForward 時,它被包含在當前的符號表中。因此,我們不需要像這樣調用函數 – printNumbers.printForward() 有時候另一個變體也很有用。在這裡,我們使用了重新命名,就像我們之前所做的一樣,以方便我們使用該函數。 此外,如果我們想要導入模組定義的所有名稱,還有另一個導入的變體。這導入除了以底線(_)開頭的名稱之外的所有名稱。但這並不是理想的做法,因為這將一組未知的名稱引入解釋器。

關於 Python 模組的常見問題

讓我們來看看與 Python 模組相關的一些常見問題。

Python 中有哪些內建模組?

有很多內建模塊在Python中。一些重要的模塊包括 – collections, datetime, logging, math, numpy, os, pip, sys, 和 time。您可以在Python shell中執行 help('modules') 命令來獲取可用模塊的列表。

模塊和包在Python中有什麼區別?

Python 包是一組Python模塊。Python模塊是單個Python文件,而Python包是一個目錄,其中包含多個Python腳本和定義包詳細信息的__init__.py文件。

我在哪裡可以找到Python模組列表?

您可以從官方的 Python模組索引 頁面找到Python模組的列表。但是,如果您正在尋找您可以使用的Python模組,那麼您可以在Python shell中執行 help('modules') 命令來獲取可用模組的列表。

Python Modules List

請檢查這個 GitHub存儲庫 以獲得最重要的Python模組列表,並通過它們的特定教程和示例程序來學習它們。

我該如何從不同目錄導入模組?

當我們嘗試導入一個Python模組時,它會查找當前目錄和PATH變量位置。因此,如果您的Python文件不在這些位置中,則將收到 ModuleNotFoundError。解決方法是導入 sys 模組,然後將所需目錄添加到其路徑變量中。下面的代碼顯示了當我們嘗試從不同目錄導入時的錯誤,以及我如何通過將其目錄添加到路徑變量中來修復它。

$ python3.7
Python 3.7.0 (v3.7.0:1bf9cc5093, Jun 26 2018, 23:26:24) 
[Clang 6.0 (clang-600.0.57)] on darwin
Type "help", "copyright", "credits" or "license" for more information.
>>> import test123
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
ModuleNotFoundError: No module named 'test123'
>>> import sys
>>> sys.path.append('/Users/pankaj/temp')
>>> import test123
>>> test123.x
10
>>> test123.foo()
foo
>>> 

Python 模組列表

有成千上萬的 Python 模組,每天都有更多的模組被開發出來。我們已為許多熱門的 Python 模組撰寫了教程。只需從下表中的連結進入,學習這些模組。

參考資料:

Source:
https://www.digitalocean.com/community/tutorials/python-modules