閉包能將狀態「封裝」在函式內部,不需全域變數、不需類,即可實現計數器、累加器等有狀態函式。本文展示最小可行實現,並對比類與生成器寫法。
def generate_counter():
CNT = [0] # 可變容器,繞過 Python 2 無 nonlocal 限制
def add_one():
CNT[0] += 1
return CNT[0]
return add_one
counter = generate_counter()
print(counter()) # 1
print(counter()) # 2
print(counter()) # 3
nonlocal)
def generate_counter():
count = 0
def add_one():
nonlocal count
count += 1
return count
return add_one
class Counter:
def __init__(self):
self.count = 0
def __call__(self):
self.count += 1
return self.count
counter = Counter()
print(counter()) # 1
def counter_gen():
i = 0
while True:
i += 1
yield i
counter = counter_gen()
print(next(counter)) # 1
print(next(counter)) # 2
| 場景 | 推薦 | 理由 |
|---|---|---|
| 極簡、單一方法、無繼承需求 | 閉包 | 代碼最少、閉包捕獲天然私有 |
| 多方法、狀態複雜、需繼承/多型 | 類 | 結構清晰、IDE 支援好 |
| 惰性產生序列、記憶體效率、for 迴圈消費 | 生成器 | 按需計算、支援 itertools |
閉包計數器是理解「狀態封裝於函式」的最佳入門範例,也是裝飾器、functools.partial、lru_cache 等高階功能的基石機制。