全部学科
Python全栈
python
NodeJS全栈
nodejs
小程序首页
📅 2026-05-19 8 分钟 ✍️ juanwangdev

Python functools 工具模块

functools 提供高阶函数工具,增强函数功能。

wraps 装饰器

保持被装饰函数的元信息。

Python
from functools import wraps

def my_decorator(func):
    @wraps(func)  # 保持 __name__, __doc__ 等
    def wrapper(*args, **kwargs):
        return func(*args, **kwargs)
    return wrapper

@my_decorator
def example():
    "示例文档"
    pass

print(example.__name__)  # example
print(example.__doc__)   # 示例文档

不使用 wraps:

Python
def bad_decorator(func):
    def wrapper(*args, **kwargs):
        return func(*args, **kwargs)
    return wrapper

@bad_decorator
def example():
    "示例文档"
    pass

print(example.__name__)  # wrapper(丢失原信息)

lru_cache 缓存

缓存函数调用结果,提升性能。

Python
from functools import lru_cache

@lru_cache(maxsize=128)
def fibonacci(n):
    if n < 2:
        return n
    return fibonacci(n - 1) + fibonacci(n - 2)

# 第一次调用计算
print(fibonacci(100))  # 快速返回

# 查看缓存信息
print(fibonacci.cache_info())
# CacheInfo(hits=99, misses=101, maxsize=128, currsize=101)

# 清除缓存
fibonacci.cache_clear()

cache 无限缓存

Python
from functools import cache

@cache  # 无大小限制
def factorial(n):
    if n < 2:
        return 1
    return n * factorial(n - 1)

print(factorial(10))

cached_property

缓存计算属性。

Python
from functools import cached_property

class DataSet:
    def __init__(self, data):
        self._data = data

    @cached_property
    def summary(self):
        "只计算一次,之后缓存"
        return {
            'count': len(self._data),
            'sum': sum(self._data),
            'avg': sum(self._data) / len(self._data)
        }

ds = DataSet([1, 2, 3, 4, 5])
print(ds.summary)  # 第一次计算
print(ds.summary)  # 使用缓存

partial 偏函数

Python
from functools import partial

def power(base, exp):
    return base ** exp

square = partial(power, exp=2)
print(square(4))  # 16

partialmethod

类方法的偏函数。

Python
from functools import partialmethod

class Button:
    def click(self, action, target):
        print(f"{action} on {target}")

    click_ok = partialmethod(click, 'Confirm', 'OK')
    click_cancel = partialmethod(click, 'Cancel', 'Cancel')

btn = Button()
btn.click_ok()      # Confirm on OK
btn.click_cancel()  # Cancel on Cancel

reduce 累积函数

Python
from functools import reduce

numbers = [1, 2, 3, 4, 5]
total = reduce(lambda x, y: x + y, numbers)
print(total)  # 15

# 带初始值
total = reduce(lambda x, y: x + y, numbers, 100)
print(total)  # 115

total_ordering 自动补全

Python
from functools import total_ordering

@total_ordering
class Number:
    def __init__(self, value):
        self.value = value

    def __eq__(self, other):
        return self.value == other.value

    def __lt__(self, other):
        return self.value < other.value

# 自动生成 __le__, __gt__, __ge__
a = Number(5)
b = Number(10)

print(a < b)   # True
print(a <= b)  # True(自动生成)
print(a > b)   # False(自动生成)
print(a >= b)  # False(自动生成)

singledispatch 单分派

Python
from functools import singledispatch

@singledispatch
def process(value):
    return f"默认处理: {value}"

@process.register
def _(value: int):
    return f"整数处理: {value * 2}"

@process.register
def _(value: str):
    return f"字符串处理: {value.upper()}"

@process.register(list)
def _(value):
    return f"列表处理: {len(value)}"

print(process(10))      # 整数处理: 20
print(process("hello")) # 字符串处理: HELLO
print(process([1,2,3])) # 列表处理: 3
print(process(3.14))    # 默认处理: 3.14

工具对比

工具用途
wraps保持函数元信息
lru_cache有大小限制的缓存
cache无限制缓存
cached_property缓存计算属性
partial创建偏函数
reduce累积处理序列
total_ordering自动补全比较方法
singledispatch类型分发函数

要点总结

  • wraps 保持装饰器函数的原有元信息
  • lru_cache 缓存结果提升性能,maxsize=None 等同 cache
  • cached_property 缓存计算属性,只计算一次
  • partial 固定部分参数创建新函数
  • reduce 累积处理序列返回单一值
  • total_ordering 只需定义一个比较方法,自动补全其他
  • singledispatch 根据参数类型分发不同实现

📝 发现内容有误?点击此处直接编辑

← 上一篇 Python 魔术方法基础
下一篇 → Python lambda 表达式
想查看更多题目和详细解析?
小程序提供完整的题库、模拟考试和详细解析
马上就来

长按或扫描二维码,立即体验

扫码体验小程序
马上就来
使用微信扫描二维码
立即体验完整题库