# Python 模塊
> 原文: [https://thepythonguru.com/python-modules/](https://thepythonguru.com/python-modules/)
* * *
于 2020 年 1 月 7 日更新
* * *
Python 模塊是一個普通的 python 文件,可以存儲函數,變量,類,常量等。模塊幫助我們組織相關代碼。 例如,python 中的`math`模塊具有與數學相關的函數。
## 創建模塊
* * *
創建一個名為`mymodule.py`的新文件并編寫以下代碼。
```py
foo = 100
def hello():
? ? print("i am from mymodule.py")
```
如您所見,我們在模塊中定義了全局變量`foo`和函數`hello()`。 現在要在程序中使用此模塊,我們首先需要使用`import`語句將其導入
```py
import mymodule
```
現在您可以使用以下代碼在`mymodule.py`中使用變量和調用函數。
```py
import mymodule
print(mymodule.foo)
print(mymodule.hello())
```
**預期輸出**:
```py
100
i am from mymodule.py
```
請記住,您需要先指定模塊名稱才能訪問其變量和函數,否則將導致錯誤。
## 結合使用`from`和`import`
* * *
使用`import`語句會導入模塊中的所有內容,如果只想訪問特定的函數或變量該怎么辦? 這是`from`語句的來源,這里是如何使用它。
```py
from mymodule import foo # this statement import only foo variable from mymodule
print(foo)
```
**預期輸出**:
```py
100
```
**注意**:
在這種情況下,您無需指定模塊名稱即可訪問變量和函數。
## `dir()`方法
* * *
`dir()`是一種內置方法,用于查找對象的所有屬性(即所有可用的類,函數,變量和常量)。 正如我們已經在 python 中討論的所有對象一樣,我們可以使用`dir()`方法來查找模塊的屬性,如下所示:
```py
dir(module_name)
```
`dir()`返回包含可用屬性名稱的字符串列表。
```py
>>> dir(mymodule)
['__builtins__', '__cached__', '__doc__', '__file__',
'__loader__', '__name__', '__package__', '__spec__', 'foo', 'hello']
```
如您所見,除了`foo`和`hello`之外,`mymodule`中還有其他屬性。 這些是 python 自動提供給所有模塊的內置屬性。
恭喜您已經完成了掌握 Python 所需的所有構建基塊!!
* * *
* * *
- 初級 Python
- python 入門
- 安裝 Python3
- 運行 python 程序
- 數據類型和變量
- Python 數字
- Python 字符串
- Python 列表
- Python 字典
- Python 元組
- 數據類型轉換
- Python 控制語句
- Python 函數
- Python 循環
- Python 數學函數
- Python 生成隨機數
- Python 文件處理
- Python 對象和類
- Python 運算符重載
- Python 繼承與多態
- Python 異常處理
- Python 模塊
- 高級 Python
- Python *args和**kwargs
- Python 生成器
- Python 正則表達式
- 使用 PIP 在 python 中安裝包
- Python virtualenv指南
- Python 遞歸函數
- __name__ == "__main__"是什么?
- Python Lambda 函數
- Python 字符串格式化
- Python 內置函數和方法
- Python abs()函數
- Python bin()函數
- Python id()函數
- Python map()函數
- Python zip()函數
- Python filter()函數
- Python reduce()函數
- Python sorted()函數
- Python enumerate()函數
- Python reversed()函數
- Python range()函數
- Python sum()函數
- Python max()函數
- Python min()函數
- Python eval()函數
- Python len()函數
- Python ord()函數
- Python chr()函數
- Python any()函數
- Python all()函數
- Python globals()函數
- Python locals()函數
- 數據庫訪問
- 安裝 Python MySQLdb
- 連接到數據庫
- MySQLdb 獲取結果
- 插入行
- 處理錯誤
- 使用fetchone()和fetchmany()獲取記錄
- 常見做法
- Python:如何讀取和寫入文件
- Python:如何讀取和寫入 CSV 文件
- 用 Python 讀寫 JSON
- 用 Python 轉儲對象