python_functools模块

functools 是Python标准库中专门用于:

  • 操作或扩展其他函数
  • 缓存计算结果
  • 实现函数装饰器
  • 减少重复代码

partial 冻结参数

作用:固定函数的部分参数,生成新函数

from functools import partial

# 原函数
def power(base, exponent):
    return base ** exponent

# 创建平方函数(固定exponent=2)
square = partial(power, exponent=2)
print(square(5))  # 输出:25

# 创建立方函数(固定base=2)
cube = partial(power, 2)
print(cube(3))

cube = partial(power, base=2)
print(cube(exponent=3))

lru_cache 智能缓存

作用:自动缓存函数结果,避免重复计算

from functools import lru_cache
import time

@lru_cache(maxsize=128)  # 缓存最近128个结果
def fibonacci(n):
    if n < 2:
        return n
    return fibonacci(n-1) + fibonacci(n-2)

# 首次计算(慢)
start = time.time()
print(fibonacci(200))
print(f"首次耗时: {time.time()-start:.4f}s")

# 再次计算(极快)
start = time.time()
print(fibonacci(200))
print(f"缓存耗时: {time.time()-start:.4f}s")

输出结果:

280571172992510140037611932413038677189525
首次耗时:0.0010s
280571172992510140037611932413038677189525
缓存耗时:0.0000s

@cache@lru_cache(maxsize=128)选择取决于具体使用的场景:

性能对比

  • @cache‌:无淘汰策略,缓存所有调用结果,适合计算结果不频繁变化且内存允许的情况下使用。例如,计算密集型任务中,若结果长期有效且调用参数固定,该方式更优。 ‌
  • @lru_cache(maxsize=128)‌:采用LRU淘汰策略,缓存容量固定为128项。当缓存满时,自动移除最近最少使用的项,适合参数组合多、计算代价高的场景。例如,频繁调用的函数或大数据量处理时,可避免内存溢出。

适用场景

  • 无限制缓存‌:若函数调用参数可哈希且结果长期有效(如常数计算、查表类函数),优先使用@cache。 ‌
  • 有限缓存‌:当参数组合多样且计算代价高(如递归调用、复杂运算),建议使用@lru_cache(maxsize=128)。 ‌

内存与效率平衡

  • 若参数类型敏感(如typed=True),两者行为差异显著:
    • @cache会缓存所有类型参数的结果
    • @lru_cache(maxsize=128)仅缓存指定类型的参数 ‌

总结:优先选择@cache进行无限制缓存,若需控制缓存容量且允许淘汰策略,则选用@lru_cache(maxsize=128)

wraps 保留元数据

from functools import wraps

def my_decorator(func):
    @wraps(func)  # 保留原函数信息
    def wrapper(*args, **kwargs):
        print("函数被调用!")
        return func(*args, **kwargs)
    return wrapper

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

# 测试元数据
print(example.__name__)  # 输出:example
print(example.__doc__)   # 输出:示例函数文档

reduce 累积计算

作用:对可迭代对象进行累积操作

from functools import reduce

# 计算阶乘
factorial = reduce(lambda x, y: x * y, range(1, 6))
print(factorial)  # 输出:120(1*2*3*4*5)

# 连接字符串
words = ["Python", "is", "awesome!"]
sentence = reduce(lambda a, b: a + " " + b, words)
print(sentence)  # 输出:Python is awesome!

total_ordering 简化比较操作

作用:只需定义__eq__和一个比较方法,自动生成全部比较运算符

from functools import total_ordering

@total_ordering
class Student:
    def __init__(self, name, score):
        self.name = name
        self.score = score
        
    def __eq__(self, other):
        return self.score == other.score
        
    def __lt__(self, other):
        return self.score < other.score

# 测试比较运算符
s1 = Student("Alice", 85)
s2 = Student("Bob", 92)
print(s1 < s2)   # True
print(s1 >= s2)  # False
print(s1 != s2)  # True

 

posted on 2025-08-08 10:34  Jasongo  阅读(34)  评论(0)    收藏  举报