Python 模組 (Module)

模組是一個包含 Python 程式碼的檔案,可以定義函數、類別和變數。使用模組可以讓程式碼更有組織、更容易重用。

什麼是模組

每個 .py 檔案就是一個模組。例如,建立一個 mymodule.py 檔案:

# mymodule.py
def greet(name):
    return f"Hello, {name}!"

def add(a, b):
    return a + b

PI = 3.14159

匯入模組

import 語法

import mymodule

print(mymodule.greet("Alice"))  # Hello, Alice!
print(mymodule.add(3, 5))       # 8
print(mymodule.PI)              # 3.14159

from...import 語法

只匯入特定的函數或變數:

from mymodule import greet, PI

print(greet("Alice"))  # Hello, Alice!
print(PI)              # 3.14159
# print(add(3, 5))     # NameError: add 沒有匯入

匯入所有內容

from mymodule import *

print(greet("Alice"))  # Hello, Alice!
print(add(3, 5))       # 8
print(PI)              # 3.14159
不建議使用 import *,因為:1. 可能會覆蓋現有的變數2. 不清楚哪些名稱被匯入 3. 難以追蹤程式碼來源

別名

import mymodule as mm

print(mm.greet("Alice"))  # Hello, Alice!

from mymodule import greet as say_hello

print(say_hello("Bob"))  # Hello, Bob!

Python 標準函式庫

Python 內建許多實用的模組:

math - 數學運算

import math

print(math.pi)         # 3.141592653589793
print(math.sqrt(16))   # 4.0
print(math.ceil(3.2))  # 4
print(math.floor(3.8)) # 3
print(math.pow(2, 3))  # 8.0

random - 隨機數

import random

print(random.random())         # 0-1 之間的隨機浮點數
print(random.randint(1, 10))   # 1-10 之間的隨機整數
print(random.choice([1, 2, 3])) # 隨機選擇一個元素

items = [1, 2, 3, 4, 5]
random.shuffle(items)  # 打亂順序
print(items)

datetime - 日期時間

from datetime import datetime, date, timedelta

now = datetime.now()
print(now)  # 2024-12-08 10:30:00.123456

today = date.today()
print(today)  # 2024-12-08

# 日期運算
tomorrow = today + timedelta(days=1)
print(tomorrow)  # 2024-12-09

os - 作業系統

import os

print(os.getcwd())           # 目前工作目錄
print(os.listdir('.'))       # 列出目錄內容
print(os.path.exists('file.txt'))  # 檢查檔案是否存在
print(os.path.join('dir', 'file.txt'))  # 組合路徑

sys - 系統參數

import sys

print(sys.version)      # Python 版本
print(sys.path)         # 模組搜尋路徑
print(sys.argv)         # 命令列參數
# sys.exit()            # 結束程式

json - JSON 處理

import json

# Python 物件轉 JSON 字串
data = {"name": "Alice", "age": 25}
json_str = json.dumps(data)
print(json_str)  # {"name": "Alice", "age": 25}

# JSON 字串轉 Python 物件
json_str = '{"name": "Bob", "age": 30}'
data = json.loads(json_str)
print(data["name"])  # Bob

模組搜尋路徑

Python 會在以下位置搜尋模組:

  1. 目前目錄
  2. PYTHONPATH 環境變數指定的目錄
  3. Python 安裝目錄
import sys
print(sys.path)

__name__ 變數

每個模組都有 __name__ 變數:

  • 直接執行時:__name__ == "__main__"
  • 被匯入時:__name__ == "模組名稱"
# mymodule.py
def main():
    print("Running as main")

if __name__ == "__main__":
    # 只有直接執行時才會執行
    main()

這個模式讓模組可以同時作為可執行程式和可匯入的模組:

# 直接執行 python mymodule.py
# 輸出: Running as main

# 匯入時不會執行 main()
import mymodule
# 沒有輸出

dir() 函數

查看模組內的所有名稱:

import math

print(dir(math))
# ['__doc__', '__name__', 'acos', 'ceil', 'cos', 'e', 'floor', ...]

重新載入模組

模組只會在第一次匯入時執行,如果需要重新載入:

import importlib
import mymodule

# 修改 mymodule.py 後重新載入
importlib.reload(mymodule)

常用標準函式庫

模組用途
os作業系統介面
sys系統參數和函數
math數學運算
random隨機數產生
datetime日期時間處理
jsonJSON 編碼/解碼
re正規表達式
collections特殊容器資料型態
itertools迭代器工具
functools高階函數工具
pathlib物件導向的路徑處理
urllibURL 處理
sqlite3SQLite 資料庫
logging日誌記錄
unittest單元測試

實際範例

# utils.py
import os
import json
from datetime import datetime

def read_json(filepath):
    """讀取 JSON 檔案"""
    with open(filepath, 'r', encoding='utf-8') as f:
        return json.load(f)

def write_json(filepath, data):
    """寫入 JSON 檔案"""
    with open(filepath, 'w', encoding='utf-8') as f:
        json.dump(data, f, indent=2, ensure_ascii=False)

def get_timestamp():
    """取得目前時間戳記"""
    return datetime.now().strftime('%Y-%m-%d %H:%M:%S')

def ensure_dir(path):
    """確保目錄存在"""
    if not os.path.exists(path):
        os.makedirs(path)
# main.py
from utils import read_json, write_json, get_timestamp

data = {"message": "Hello", "time": get_timestamp()}
write_json("output.json", data)

loaded = read_json("output.json")
print(loaded)