Python中的函数式编程工具:functools模块详解
字数 1124 2025-11-27 06:54:25
Python中的函数式编程工具:functools模块详解
1. 模块概述
functools是Python标准库中用于高阶函数(操作或返回其他函数的函数)的模块,提供了一系列增强函数功能的工具。常见应用场景包括函数缓存、部分参数应用、函数包装等。下面我们逐步解析核心功能。
2. 核心工具详解
2.1 functools.partial:部分参数应用
- 作用:固定函数的部分参数,生成一个新函数,减少重复传参。
- 示例:
from functools import partial def multiply(x, y): return x * y # 固定第一个参数x=2,生成新函数double double = partial(multiply, 2) print(double(5)) # 输出10(等价于multiply(2, 5)) - 原理:
partial内部通过闭包保存原函数和已固定的参数,调用时合并新参数与固定参数。
2.2 functools.lru_cache:函数缓存
- 作用:通过LRU(最近最少使用)算法缓存函数结果,避免重复计算。
- 参数:
maxsize:缓存大小(默认128,设为None表示无限制)。typed:是否区分参数类型(如3和3.0视为不同键)。
- 示例:
from functools import lru_cache @lru_cache(maxsize=32) def fib(n): if n < 2: return n return fib(n-1) + fib(n-2) print(fib(10)) # 第1次计算,结果被缓存 print(fib(10)) # 直接返回缓存结果 - 注意:缓存的函数参数必须是可哈希的(如不可变类型)。
2.3 functools.wraps:保留函数元信息
- 问题背景:使用装饰器时,原函数的
__name__、__doc__等元信息会被装饰器覆盖。 - 解决方案:用
wraps装饰器保留原函数的属性。 - 示例:
from functools import wraps def my_decorator(func): @wraps(func) # 将func的元信息复制到wrapper函数 def wrapper(*args, **kwargs): print("函数被调用") return func(*args, **kwargs) return wrapper @my_decorator def example(): """示例函数""" pass print(example.__name__) # 输出"example"(而非"wrapper") print(example.__doc__) # 输出"示例函数"
2.4 functools.singledispatch:单分派泛型函数
- 作用:根据第一个参数的类型选择不同的函数实现(类似重载)。
- 示例:
from functools import singledispatch @singledispatch def process(arg): print(f"默认处理: {arg}") @process.register def _(arg: int): print(f"处理整数: {arg}") @process.register def _(arg: list): print(f"处理列表: {arg}") process(10) # 输出"处理整数: 10" process([1,2]) # 输出"处理列表: [1, 2]" process("hi") # 输出"默认处理: hi"
2.5 functools.reduce:累积计算
- 作用:对序列中的元素依次应用函数,逐步合并结果。
- 示例:
from functools import reduce numbers = [1, 2, 3, 4] result = reduce(lambda x, y: x * y, numbers) # 1*2*3*4=24 print(result) # 输出24 - 扩展:可提供初始值(如
reduce(lambda x,y: x+y, [1,2], 10)结果为13)。
3. 进阶工具
3.1 functools.cached_property(Python 3.8+)
- 作用:将方法转换为属性,结果计算一次后缓存。
- 示例:
from functools import cached_property class Data: def __init__(self, n): self.n = n @cached_property def expensive_computation(self): print("计算中...") return self.n * 2 d = Data(10) print(d.expensive_computation) # 输出"计算中..."后返回20 print(d.expensive_computation) # 直接返回缓存值20
3.2 functools.total_ordering(Python 3.2+)
- 作用:自动生成缺失的比较方法(如
<,>=),只需定义__eq__和__lt__等至少一个方法。 - 示例:
from functools import total_ordering @total_ordering class Student: def __init__(self, score): self.score = score def __eq__(self, other): return self.score == other.score def __lt__(self, other): return self.score < other.score # 自动生成__le__、__gt__等方法 s1, s2 = Student(80), Student(90) print(s1 <= s2) # True(即使未明确定义__le__)
4. 总结
partial:减少参数重复传递。lru_cache:优化递归或计算密集型函数。wraps:保留装饰函数的元信息。singledispatch:实现类型驱动的函数重载。reduce:替代循环进行累积操作。- 其他工具如
cached_property、total_ordering等进一步简化代码。
通过灵活组合这些工具,可以写出更简洁、高效且可维护的函数式代码。