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

相关推荐
穿西装的水獭12 分钟前
python将Excel数据写进图片中
开发语言·python·excel
老友@31 分钟前
Java Excel 导出:EasyExcel 使用详解
java·开发语言·excel·easyexcel·excel导出
xiaoxiongip66638 分钟前
假设两个设备在不同网段,网关怎么设置才能通呢
网络·爬虫·python·https·智能路由器
逻极1 小时前
Scikit-learn 实战:15 分钟构建生产级中国房价预测模型
python·机器学习·scikit-learn
行板Andante1 小时前
AttributeError: ‘super‘ object has no attribute ‘sklearn_tags‘解决
人工智能·python·sklearn
tryCbest1 小时前
Python基础之爬虫技术(一)
开发语言·爬虫·python
husterlichf1 小时前
逻辑回归以及python(sklearn)详解
python·逻辑回归·sklearn
hixiong1231 小时前
C# OpenCVSharp实现Hand Pose Estimation Mediapipe
开发语言·opencv·ai·c#·手势识别
集成显卡1 小时前
AI取名大师 | PM2 部署 Bun.js 应用及配置 Let‘s Encrypt 免费 HTTPS 证书
开发语言·javascript·人工智能
AI小云1 小时前
【Numpy数据运算】数组间运算
开发语言·python·numpy