Python 函数式编程的 8 大核心技巧,不允许你还不会
函数式编程是一种强调使用纯函数、避免共享状态和可变数据的编程范式。Python 虽然不是纯函数式语言,但提供了丰富的函数式编程特性。以下是 Python 函数式编程的 8 个核心技巧:
1. 纯函数 (Pure Functions)
特点:相同输入永远得到相同输出,没有副作用
# 纯函数示例
def add(a, b):
return a + b
# 非纯函数示例(有副作用)
total = 0
def impure_add(a):
global total
total += a
return total
优势:
- 更易于测试和调试
- 更易于并行化
- 更易于推理和验证
2. 高阶函数 (Higher-Order Functions)
特点:接受函数作为参数或返回函数作为结果
# map 应用函数到可迭代对象
numbers = [1, 2, 3]
squared = list(map(lambda x: x**2, numbers)) # [1, 4, 9]
# filter 过滤元素
evens = list(filter(lambda x: x % 2 == 0, numbers)) # [2]
# sorted 自定义排序
words = ['apple', 'banana', 'cherry']
sorted_words = sorted(words, key=lambda x: len(x)) # 按长度排序
3. 匿名函数 (Lambda Functions)
特点:一次性使用的简单函数
# 基本语法:lambda 参数: 表达式
square = lambda x: x**2
print(square(5)) # 25
# 在排序中使用
students = [{'name': 'Alice', 'score': 90},
{'name': 'Bob', 'score': 85}]
sorted_students = sorted(students, key=lambda s: s['score'], reverse=True)
最佳实践:
- 只用于简单操作
- 复杂逻辑应该使用常规函数
- 避免嵌套多层 lambda
4. 闭包 (Closures)
特点:内部函数记住并访问外部函数的变量
def make_multiplier(factor):
def multiplier(x):
return x * factor
return multiplier
double = make_multiplier(2)
triple = make_multiplier(3)
print(double(5)) # 10
print(triple(5)) # 15
应用场景:
- 装饰器
- 回调函数
- 函数工厂
5. 装饰器 (Decorators)
特点:修改或增强函数行为而不改变其定义
from functools import wraps
def timer(func):
@wraps(func)
def wrapper(*args, **kwargs):
import time
start = time.time()
result = func(*args, **kwargs)
end = time.time()
print(f"{func.__name__} 执行时间: {end-start:.4f}秒")
return result
return wrapper
@timer
def long_running_function():
import time
time.sleep(2)
long_running_function()
常见用途:
- 日志记录
- 性能测试
- 权限验证
- 输入验证
6. 不可变数据 (Immutable Data)
特点:创建后不能修改的数据结构
# 使用元组代替列表
point = (1, 2) # 不可变
# 使用 frozenset 代替 set
fs = frozenset([1, 2, 3])
# 使用 namedtuple
from collections import namedtuple
Person = namedtuple('Person', ['name', 'age'])
p = Person('Alice', 25)
优势:
- 线程安全
- 易于推理
- 避免意外的修改
7. 递归 (Recursion)
特点:函数调用自身来解决问题
# 阶乘函数
def factorial(n):
return 1 if n <= 1 else n * factorial(n-1)
# 尾递归优化(Python 不支持自动优化,但可以这样写)
def factorial_tail(n, acc=1):
return acc if n <= 1 else factorial_tail(n-1, acc*n)
注意事项:
- Python 有递归深度限制(默认约1000)
- 对于深递归考虑使用迭代
- 尾递归可以避免栈溢出(但Python不优化)
8. 函数组合 (Function Composition)
特点:将多个函数组合成一个新函数
from functools import reduce
def compose(*funcs):
"""从右到左组合函数"""
return reduce(lambda f, g: lambda x: f(g(x)), funcs, lambda x: x)
# 示例函数
add1 = lambda x: x + 1
mul2 = lambda x: x * 2
square = lambda x: x**2
# 组合函数:square(mul2(add1(x)))
composed = compose(square, mul2, add1)
print(composed(3)) # ((3 + 1) * 2)^2 = 64
替代方案:
# 使用管道式处理(从左到右)
def pipe(*funcs):
return reduce(lambda f, g: lambda x: g(f(x)), funcs, lambda x: x)
piped = pipe(add1, mul2, square)
print(piped(3)) # 同上结果
进阶技巧:惰性求值 (Lazy Evaluation)
# 生成器表达式
numbers = (x**2 for x in range(1000000)) # 不立即计算
# itertools 模块
from itertools import islice, count
# 无限序列
natural_numbers = count(1)
first_10 = islice(natural_numbers, 10)
print(list(first_10)) # [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
实际应用示例
数据处理管道
from functools import partial
# 构建处理管道
process = partial(pipe,
str.strip,
str.lower,
lambda s: s.replace(' ', '_'),
lambda s: s.encode('utf-8'))
result = process(" Hello World ")
print(result) # b'hello_world'
函数式风格的状态管理
# 使用不可变数据和纯函数管理状态
def update_user(user, **changes):
return user._replace(**changes)
user = Person('Alice', 25)
new_user = update_user(user, age=26)
这些核心技巧可以帮助你写出更简洁、更模块化、更易于维护的 Python 代码。函数式编程特别适合数据处理、转换和管道操作等场景。