🧠 一、模块定位
functools 是 Python 的函数式编程支持库,其目标是提供工具来:
- 增强函数的功能
- 操作函数对象(函数即一等公民)
- 支持函数式编程范式(如惰性求值、偏应用、缓存、分派等)
📦 二、详细讲解各个函数
1️⃣ functools.partial
✅ 作用:
创建一个新的函数,将原函数的部分参数固定(即预填充),返回一个新的“偏函数”。
✅ 实现原理:
底层使用 Partial 类,保存 func、args 和 keywords,调用时组合这三者与新的参数一起调用原函数。
✅ 示例:
from functools import partial
def power(base, exponent):
return base ** exponent
square = partial(power, exponent=2)
print(square(3)) # 9
2️⃣ functools.wraps
✅ 作用:
用来修饰自定义装饰器,保留被装饰函数的元信息,如 __name__, __doc__, __annotations__ 等。
✅ 实现原理:
本质是 update_wrapper() 的简写形式,作用是将 wrapped 函数的属性复制到 wrapper 上。
✅ 示例:
from functools import wraps
def logger(func):
@wraps(func)
def wrapper(*args, **kwargs):
print(f"Calling {func.__name__}")
return func(*args, **kwargs)
return wrapper
3️⃣ functools.lru_cache
✅ 作用:
自动缓存函数的结果,用于提高函数(尤其是递归函数)的性能。
✅ 参数:
maxsize: 缓存大小(设为None表示无限)typed: 是否区分参数类型(如1vs1.0)
✅ 实现原理:
- 使用 Least Recently Used(LRU)算法
- 内部使用
OrderedDict(<=Py3.7)或dict+双链表(>=Py3.8) - 自动清除最久未使用的缓存项
✅ 示例:
@lru_cache(maxsize=128)
def fibonacci(n):
if n < 2:
return n
return fibonacci(n-1) + fibonacci(n-2)
4️⃣ functools.reduce
✅ 作用:
对可迭代对象中的项进行累积计算,从左到右依次合并,最终返回一个值。
✅ 原型:
reduce(function, iterable[, initializer])
✅ 示例:
from functools import reduce
nums = [1, 2, 3, 4]
result = reduce(lambda x, y: x + y, nums) # 1+2+3+4
5️⃣ functools.singledispatch
✅ 作用:
实现 单分派泛型函数 —— 一个函数根据参数类型的不同自动分派到不同的实现。
✅ 应用场景:
- 实现类型相关逻辑而不需要手动写
if isinstance(...)语句 - 模拟多态
✅ 示例:
from functools import singledispatch
@singledispatch
def process(value):
print(f"Default: {value}")
@process.register(int)
def _(value):
print(f"Integer: {value}")
@process.register(list)
def _(value):
print(f"List: {value}")
process(42) # Integer
process("hello") # Default
process([1, 2]) # List
6️⃣ functools.total_ordering
✅ 作用:
自动为自定义类生成所有比较操作,只需实现 __lt__ 和一个等号类操作(如 __eq__)
✅ 示例:
from functools import total_ordering
@total_ordering
class Person:
def __init__(self, age):
self.age = age
def __eq__(self, other):
return self.age == other.age
def __lt__(self, other):
return self.age < other.age
只写了
__eq__和__lt__,其他如__le__,__gt__,__ge__都自动生成。
7️⃣ functools.cached_property(Python 3.8+)
✅ 作用:
类似 @property,但会缓存第一次计算的结果,后续访问不会再执行函数体。
✅ 示例:
from functools import cached_property
class Circle:
def __init__(self, radius):
self.radius = radius
@cached_property
def area(self):
print("Computing area...")
return 3.14 * self.radius ** 2
c = Circle(10)
print(c.area) # 计算一次
print(c.area) # 直接返回缓存值
8️⃣ functools.partialmethod
✅ 用于:类中创建带默认参数的方法(是 partial 的面向对象版本)
✅ 示例:
from functools import partialmethod
class Logger:
def log(self, level, msg):
print(f"[{level}] {msg}")
info = partialmethod(log, "INFO")
error = partialmethod(log, "ERROR")
log = Logger()
log.info("Initialization complete.") # [INFO] Initialization complete.
9️⃣ functools.update_wrapper(底层函数)
✅ 作用:
复制函数的元信息到包装器函数中,是 wraps() 的实现基础。
✅ 用法:
from functools import update_wrapper
def decorator(func):
def wrapper(*args, **kwargs):
return func(*args, **kwargs)
update_wrapper(wrapper, func)
return wrapper
1️⃣0️⃣ functools.cache(Python 3.9+)
✅ 更简单的缓存方式:
from functools import cache
@cache
def square(n):
return n * n
相当于 lru_cache(maxsize=None)。
📚 三、高阶应用场景总结
| 任务 | 函数 |
|---|---|
| 缓存递归函数结果 | lru_cache / cache |
| 写性能优化装饰器 | wraps, update_wrapper |
| 多类型支持的函数 | singledispatch |
| 实现类的懒加载属性 | cached_property |
| 自定义类比较 | total_ordering |
| 提前绑定参数 | partial, partialmethod |
| 组合函数调用 | reduce |
| 编写可读性更强的装饰器 | wraps |
📌 小结
functools 是函数式编程和面向对象编程之间的桥梁,可以:
- 提高代码的抽象程度
- 增强函数的功能与性能
- 保持代码可读性和结构简洁性
1269

被折叠的 条评论
为什么被折叠?



