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

相关推荐
兵慌码乱4 小时前
面向桌面端的资产管理系统分层架构设计与核心模块实现
python·系统架构·sqlite·pyqt5·数据库设计·桌面应用开发·mvc架构
hboot6 小时前
AI工程师第三课 - 机器学习基础
python·scikit-learn·kaggle
顾林海11 小时前
Agent入门阶段-编程基础-Python:流程控制
python·agent·ai编程
呱呱复呱呱13 小时前
Django CBV 源码解读:一个请求是怎么找到你的 get() 方法的
python·django
曲幽18 小时前
刚部署的 LibreTranslate 频频翻车?我掏出了 20 年前的 StarDict 词典,用 FastAPI 搭了个本地词典翻译 API
python·fastapi·web·translate·goldendict·libretranslate·stardict·pystardict
荣码18 小时前
用Streamlit给AI应用套个界面,10行代码出Web页面
java·python
兵慌码乱1 天前
基于Python+PyQt5+SQLite的药房管理系统实现:事务一致性与界面解耦全流程解析
python·sqlite·信号与槽·pyqt5·数据库设计·桌面应用开发·事务处理
金銀銅鐵1 天前
[Python] 体验用欧几里得算法计算最大公约数的过程
python·数学
FreakStudio1 天前
W55MH32L-EVB 上手测评:硬件 TCP/IP 加持的以太网单片机,MicroPython 零门槛开发
python·单片机·嵌入式·大学生·面向对象·并行计算·电子diy·电子计算机
用户0332126663671 天前
使用 Python 从零创建 Word 文档
python