Python面试题:在 Python 中,如何使用 `functools` 模块?

functools 模块提供了几个高阶函数和调用工具,以便在编写函数时更简洁和更强大。以下是 functools 模块的一些主要功能和使用示例:

1. functools.partial

partial 函数用于固定函数的部分参数,从而创建一个新的函数。它非常适合在需要重复调用同一个函数但有些参数固定不变的情况下。

python 复制代码
from functools import partial

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

# 创建一个计算平方的函数
square = partial(power, exponent=2)
print(square(3))  # 输出: 9

# 创建一个计算立方的函数
cube = partial(power, exponent=3)
print(cube(3))  # 输出: 27

2. functools.reduce

reduce 函数用于对序列中的元素进行累计计算。它接受一个二元函数和一个序列,依次将二元函数应用于序列的元素,从而将序列简化为单个值。

python 复制代码
from functools import reduce

# 计算序列的累积和
numbers = [1, 2, 3, 4, 5]
sum_result = reduce(lambda x, y: x + y, numbers)
print(sum_result)  # 输出: 15

# 计算序列的累积乘积
product_result = reduce(lambda x, y: x * y, numbers)
print(product_result)  # 输出: 120

3. functools.lru_cache

lru_cache 装饰器用于缓存函数的返回结果,以便在相同输入下快速返回结果,从而提高性能。它常用于需要频繁调用且结果重复的函数。

python 复制代码
from functools import lru_cache

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

print(fibonacci(10))  # 输出: 55
print(fibonacci.cache_info())  # 输出缓存信息

4. functools.wraps

wraps 装饰器用于编写装饰器时保持被装饰函数的元数据(如文档字符串和函数名)。它有助于调试和维护。

python 复制代码
from functools import wraps

def my_decorator(func):
    @wraps(func)
    def wrapper(*args, **kwargs):
        print("Something is happening before the function is called.")
        result = func(*args, **kwargs)
        print("Something is happening after the function is called.")
        return result
    return wrapper

@my_decorator
def say_hello(name):
    """Greet someone by name."""
    print(f"Hello, {name}!")

say_hello("Alice")
print(say_hello.__name__)  # 输出: say_hello
print(say_hello.__doc__)   # 输出: Greet someone by name.

5. functools.total_ordering

total_ordering 装饰器用于简化实现具有完全排序的类。只需实现 __eq__ 和一个其他比较方法(如 __lt__),它就会自动生成其他比较方法。

python 复制代码
from functools import total_ordering

@total_ordering
class Person:
    def __init__(self, name, age):
        self.name = name
        self.age = age

    def __eq__(self, other):
        if not isinstance(other, Person):
            return NotImplemented
        return self.age == other.age

    def __lt__(self, other):
        if not isinstance(other, Person):
            return NotImplemented
        return self.age < other.age

# 比较两个对象
alice = Person("Alice", 30)
bob = Person("Bob", 25)

print(alice > bob)  # 输出: True
print(alice >= bob) # 输出: True
print(alice < bob)  # 输出: False
print(alice <= bob) # 输出: False

这些是 functools 模块中一些常用的功能和示例。这个模块提供了许多有用的工具,可以帮助你编写更高效和更易维护的代码。

相关推荐
AI探索者12 小时前
LangGraph StateGraph 实战:状态机聊天机器人构建指南
python
AI探索者12 小时前
LangGraph 入门:构建带记忆功能的天气查询 Agent
python
FishCoderh14 小时前
Python自动化办公实战:批量重命名文件,告别手动操作
python
躺平大鹅14 小时前
Python函数入门详解(定义+调用+参数)
python
曲幽15 小时前
我用FastAPI接ollama大模型,差点被asyncio整崩溃(附对话窗口实战)
python·fastapi·web·async·httpx·asyncio·ollama
两万五千个小时19 小时前
落地实现 Anthropic Multi-Agent Research System
人工智能·python·架构
哈里谢顿21 小时前
Python 高并发服务限流终极方案:从原理到生产落地(2026 实战指南)
python
用户8356290780511 天前
无需 Office:Python 批量转换 PPT 为图片
后端·python
markfeng82 天前
Python+Django+H5+MySQL项目搭建
python·django