# 命名函數:複雜邏輯、需復用、需文檔字符串
def add(x, y):
"""返回兩數之和"""
return x + y
# 匿名函數:簡單、一次性、作為參數傳遞
lambda_add = lambda x, y: x + y
原則:需命名時用 def;臨時、簡單、作為參數時用 lambda。切勿為 lambda 起名(違背初衷)。
add_a = add # 別名
print(add_a(1, 2)) # 3
# 函數作為值存入數據結構
ops = {'+': add, '-': lambda x,y: x-y}
print(ops['+'](3, 4)) # 7
函數對象可像普通值一樣傳遞、存儲、返回,這是高階函數的基礎。
def outer():
n = 1
def inner():
print(n) # 讀取外部變量
inner()
n = 'x'
inner() # 打印 'x',閉包綁定的是變量名而非值
outer()
# 輸出: 1 然后 'x'
閉包本質:函數對象 + 綁定的自由變量環境。每次調用 outer() 都會創建新的 inner 閉包,環境相互隔離。
Python 3 修改外部變量:使用 nonlocal 關鍵字:
def counter():
count = 0
def inc():
nonlocal count
count += 1
return count
return inc
c = counter()
print(c(), c(), c()) # 1 2 3
將通用控制流抽象為高階函數,具體操作作為參數傳入:
def reduce_(func, seq, initial):
result = initial
for item in seq:
result = func(result, item)
return result
# 求和
print(reduce_(lambda a,b: a+b, [1,2,3,4], 0)) # 10
# 求積
print(reduce_(lambda a,b: a*b, [1,2,3,4], 1)) # 24
# 找最大值
print(reduce_(lambda a,b: a if a>b else b, [3,1,4,2], float('-inf'))) # 4
這就是 functools.reduce 的核心邏輯。內置 map/filter 同理。
def add_to(n):
"""返回一個『加 n』的函數"""
return lambda x: x + n
add10 = add_to(10)
print(add10(5)) # 15
# 標準庫實現:functools.partial
from functools import partial
add10 = partial(operator.add, 10)
print(add10(5)) # 15
偏函數:預先綁定部分參數,生成新函數等待剩餘參數。廣泛用於回調配置、API 客戶端預設參數等場景。
from functools import partial
import operator
data = [1, 2, 3, 4, 5]
# 管道:過濾偶數 -> 平方 -> 求和
pipeline = partial(reduce_, operator.add, 0) # 固定求和邏輯
result = pipeline(map(lambda x: x**2, filter(lambda x: x%2==0, data)))
print(result) # 20 (2^2 + 4^2)
結合 partial、map/filter、reduce,可構建聲明式、可組合的數據處理流水線。
def 定義命名函數,lambda 定義匿名函數。functools.partial 是偏函數的標準實現。