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

相关推荐
WJX_KOI4 小时前
Open Notebook 一个开源的结合AI的记笔记软件
python
喜欢吃燃面5 小时前
Linux:环境变量
linux·开发语言·学习
0思必得05 小时前
[Web自动化] 反爬虫
前端·爬虫·python·selenium·自动化
徐徐同学5 小时前
cpolar为IT-Tools 解锁公网访问,远程开发再也不卡壳
java·开发语言·分布式
LawrenceLan5 小时前
Flutter 零基础入门(二十六):StatefulWidget 与状态更新 setState
开发语言·前端·flutter·dart
2301_822382765 小时前
Python上下文管理器(with语句)的原理与实践
jvm·数据库·python
m0_748229995 小时前
Laravel8.X核心功能全解析
开发语言·数据库·php
喵手5 小时前
Python爬虫实战:从零搭建字体库爬虫 - requests+lxml 实战采集字体网字体信息数据(附 CSV 导出)!
爬虫·python·爬虫实战·零基础python爬虫教学·csv导出·采集字体库数据·字体库字体信息采集
qq_192779876 小时前
C++模块化编程指南
开发语言·c++·算法
2301_790300966 小时前
Python深度学习入门:TensorFlow 2.0/Keras实战
jvm·数据库·python