【重要】functools库函数简介及简单用法示例

【重要】functools库函数简介及简单用法示例
functools提供了一些用于函数操作的函数,如partial、lru_cache等,方便进行函数式编程。

表格部分

序号 函数名 简介
1 partial 创建一个新的可调用对象,固定原函数的部分参数
2 lru_cache 缓存函数调用的结果,基于LRU(最近最少使用)策略
3 total_ordering 通过实现一个或少数几个关键比较方法,自动为一个类生成所有必要的比较方法
4 wraps 在编写装饰器时,保持被装饰函数的元信息(如名称、文档字符串、注解等)不变
5 cmp_to_key 将旧式的比较函数转换为可用于排序的键函数
6 reduce 对一个可迭代对象应用一个累积函数,返回单一结果

函数示例部分

partial示例

from functools import partial

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

# 创建一个固定底数为2的新函数
square = partial(power, base=2)

# 调用新函数只需传递指数
print(square(3))  # 输出: 8

lru_cache示例

from functools import lru_cache

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

print(fibonacci(20))  # 第一次调用进行计算
print(fibonacci(20))  # 第二次调用直接使用缓存

total_ordering示例

from functools import total_ordering

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

    def __eq__(self, other):
        return self.name == other.name and self.age == other.age

    def __lt__(self, other):
        return self.age < other.age

p1 = Person("Alice", 25)
p2 = Person("Bob", 30)

print(p1 <= p2)  # 输出: True
print(p1 > p2)   # 输出: False

wraps示例

from functools import wraps

def add_logging(func):
    @wraps(func)
    def wrapper(*args, **kwargs):
        print(f"Calling {func.__name__} with arguments {args}, {kwargs}")
        result = func(*args, **kwargs)
        print(f"{func.__name__} returned: {result}")
        return result
    return wrapper

@add_logging
def greet(name):
    """Greet someone by their name."""
    return f"Hello, {name}!"

print(greet.__name__)  # 输出: greet
print(greet.__doc__)   # 输出: Greet someone by their name.
greet("Alice")        # 输出: Calling greet with arguments ('Alice',), {} 和 "greet returned: Hello, Alice!"

cmp_to_key示例

from functools import cmp_to_key

def compare_names(name1, name2):
    if name1 < name2:
        return -1
    elif name1 > name2:
        return 1
    else:
        return 0

names = ["Alice", "Bob", "Charlie", "David"]

# 使用旧式比较函数进行排序
sorted_names = sorted(names, key=cmp_to_key(compare_names))

print(sorted_names)  # 输出: ['Alice', 'Bob', 'Charlie', 'David']

reduce示例

from functools import reduce

numbers = [1, 2, 3, 4, 5]

# 计算列表元素的乘积
product = reduce(lambda x, y: x * y, numbers)

print(product)  # 输出: 120

这样,表格部分更加简洁,而每个函数的用法示例则清晰地展示在下方,便于阅读和理解。

posted @ 2024-12-19 09:37  nxhujiee  阅读(74)  评论(0)    收藏  举报