>本文探討了Python的模塊化編程概念:模塊和軟件包。 我們將介紹創建模塊,定義其中的功能和類,並在各個項目中使用它們。 我們還將通過將相關模塊組織到目錄中,從軟件包導入模塊並利用Python的內置資源來檢查包裝創建。 到最後,您將了解如何有效地構造代碼,以實現可維護性,可重複性和可讀性。
密鑰概念:
__all__
屬性。 模塊:構建塊>
python模塊是一個包含Python代碼的單個。 這是一個獨立的單元,可進口到其他程序中。 這促進了:
.py
databaseConnection.py
:
該模塊包含一個變量和兩個函數。 您可以直接運行它()或將其導入其他模塊。 sample.py
>
<code class="language-python"># sample.py sample_variable = "Module variable" def greet(name): return f"Hello, {name}!" def sum_numbers(a, b): return a + b print(sample_variable) print(greet("Alice")) print(sum_numbers(2, 3))</code>使用模塊:
python sample.py
>語句:導入整個模塊。
>import
<code class="language-python"># another_module.py import sample print(sample.sample_variable) print(sample.greet("Bob"))</code>
from
關鍵字:<code class="language-python"># another_module.py from sample import greet, sum_numbers print(greet("Charlie")) print(sum_numbers(4, 5))</code>
as
軟件包:組織模塊軟件包將相關模塊組織到目錄中。 當目錄包含__init__.py
>文件時(可以為空)時,將成為一個包。 這允許層次結構(子包)。
構建和管理軟件包:
>示例結構:
<code class="language-python"># sample.py sample_variable = "Module variable" def greet(name): return f"Hello, {name}!" def sum_numbers(a, b): return a + b print(sample_variable) print(greet("Alice")) print(sum_numbers(2, 3))</code>
my_package
和subpackage
是由於其__init__.py
文件而引起的軟件包。
>從軟件包導入:
<code class="language-python"># another_module.py import sample print(sample.sample_variable) print(sample.greet("Bob"))</code>
.
)在軟件包中指定相對路徑。 (謹慎使用,尤其是在較大的項目中)。 __all__
>屬性:
>在模塊的__all__
中__init__.py
屬性控制使用from package import *
時導入的內容。 它列出了要導入的名稱。 這可以促進更好的控制,並防止意外進口內部要素。
> python標準庫和第三方套件:> Python標準庫提供了許多內置模塊(例如,
,,os
>。 math
安裝
json
pip
包裝和分發:
>>有助於創建可分配的軟件包(源和二進制)。 >將軟件包上傳到PYPI。 適當的版本控制,文檔,許可和測試對於成功分發至關重要。
>setuptools
結論:twine
以上是了解Python中的模塊和包裝的詳細內容。更多資訊請關注PHP中文網其他相關文章!