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

相关推荐
虾球xz8 分钟前
CppCon 2015 学习:Reactive Stream Processing in Industrial IoT using DDS and Rx
开发语言·c++·物联网·学习
工业互联网专业15 分钟前
基于django+vue的健身房管理系统-vue
vue.js·python·django·毕业设计·源码·课程设计·健身房管理系统
aischang32 分钟前
统信桌面专业版如何使用python开发平台jupyter
开发语言·python·jupyter·统信uos
红鼻子时代35 分钟前
Django RBAC项目后端实战 - 03 DRF权限控制实现
后端·python·django·rabc
敲键盘的小夜猫42 分钟前
大模型链路调试平台之LangSmith实战指南
python·langchain
狐凄1 小时前
Python实例题:Python计算概率论
开发语言·python·概率论
Y3174291 小时前
python Day46 学习(日志Day15复习)
python·学习·机器学习
这里有鱼汤1 小时前
一文读懂量化交易中最常用的5种均线,附源码,建议收藏
后端·python
学不会就看1 小时前
selenium学习实战【Python爬虫】
python·学习·selenium
q567315231 小时前
分布式增量爬虫实现方案
开发语言·分布式·爬虫·python