Python 标准库functools高阶函数用法

简介: Python 标准库functools高阶函数用法

functoolsPython 标准库中的一个模块,它提供了一系列高阶函数和操作函数的工具。这些工具函数在函数式编程中非常有用,可以帮助我们以更加声明式和抽象的方式处理函数。在这篇文章中,我们将介绍 functools 模块中的一些常用函数和它们的用途。

>>> import functools

>>> functools.__all__

['update_wrapper', 'wraps', 'WRAPPER_ASSIGNMENTS', 'WRAPPER_UPDATES', 'total_ordering', 'cache', 'cmp_to_key', 'lru_cache', 'reduce', 'partial', 'partialmethod', 'singledispatch', 'singledispatchmethod', 'cached_property']

>>> dir(functools)

['GenericAlias', 'RLock', 'WRAPPER_ASSIGNMENTS', 'WRAPPER_UPDATES', '_CacheInfo', '_HashedSeq', '_NOT_FOUND', '__all__', '__builtins__', '__cached__', '__doc__', '__file__', '__loader__', '__name__', '__package__', '__spec__', '_c3_merge', '_c3_mro', '_compose_mro', '_convert', '_find_impl', '_ge_from_gt', '_ge_from_le', '_ge_from_lt', '_gt_from_ge', '_gt_from_le', '_gt_from_lt', '_initial_missing', '_le_from_ge', '_le_from_gt', '_le_from_lt', '_lru_cache_wrapper', '_lt_from_ge', '_lt_from_gt', '_lt_from_le', '_make_key', '_unwrap_partial', 'cache', 'cached_property', 'cmp_to_key', 'get_cache_token', 'lru_cache', 'namedtuple', 'partial', 'partialmethod', 'recursive_repr', 'reduce', 'singledispatch', 'singledispatchmethod', 'total_ordering', 'update_wrapper', 'wraps']

1. partial

partial 函数是 functools 模块中最著名的函数之一。它用于创建一个新的部分函数,这个新函数固定了原函数的一些参数,并且可以接受更少的参数。这在需要重用函数或者在多个地方使用相同参数的函数时非常有用。

用法示例
from functools import partial
 
def multiply(x, y):
    return x * y
 
# 创建一个新函数,它固定了 multiply 函数的第一个参数为 2
double = partial(multiply, 2)
result = double(5)  # 相当于 multiply(2, 5)
 
print(result)  # 输出: 10

2. reduce

reduce 函数不是 Python 标准库的内置函数,但它是 functools 模块的一部分。reduce 函数接受一个函数和一个迭代器作为参数,并将传入的函数应用于所有元素,从左到右,以累积结果。这在需要进行累积计算时非常有用。

用法示例
from functools import reduce
 
def add(x, y):
    return x + y
 
numbers = [1, 2, 3, 4, 5]
result = reduce(add, numbers)
 
print(result)  # 输出: 15

3. total_ordering

total_ordering 是一个类装饰器,它用于自动为类生成比较方法。当你定义了一个类并且实现了它的 __eq____hash__ 方法时,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, self.age) == (other.name, other.age)
 
    def __hash__(self):
        return hash((self.name, self.age))
 
# 现在 Person 类支持所有的比较操作
p1 = Person("Alice", 30)
p2 = Person("Alice", 30)
p3 = Person("Bob", 35)
 
print(p1 < p2)  # 输出: False
print(p1 < p3)  # 输出: True

4. cmp_to_key

cmp_to_key 函数用于将比较函数转换为键函数。

用法示例
from functools import cmp_to_key
 
def compare(x, y):
    return (x > y) - (x < y)
 
# 使用 cmp_to_key 将 compare 函数转换为键函数
key_func = cmp_to_key(compare)
 
numbers = [3, 1, 4, 1, 5, 9, 2, 6, 5]
sorted_numbers = sorted(numbers, key=key_func)
 
print(sorted_numbers)  # 输出排序后的数字列表

5. lru_cache

lru_cache 是一个函数装饰器,它用于缓存函数的结果,以便相同的参数在未来的调用中可以快速检索。这在需要优化函数性能,特别是对于计算密集型函数时非常有用。

用法示例
from functools import lru_cache
 
@lru_cache(maxsize=128)
def fibonacci(n):
    if n < 2:
        return n
    return fibonacci(n - 1) + fibonacci(n - 2)
 
# 调用 fibonacci 函数时,结果会被缓存
print(fibonacci(10))  # 输出: 55

6. singledispatch

singledispatch 是一个通用装饰器,它用于实现单分派通用函数。它允许您根据第一个参数的类型来选择不同的实现。

用法示例
from functools import singledispatch
 
@singledispatch
def my_function(arg):
    return f"No implementation for {type(arg)}"
 
@my_function.register(int)
def _(arg):
    return f"The integer is {arg}"
 
@my_function.register(str)
def _(arg):
    return f"The string is {arg}"
 
print(my_function(42))  # 输出: The integer is 42
print(my_function("hello"))  # 输出: The string is hello

7. update_wrapper

update_wrapper 函数用于更新一个函数的__name____doc____annotations____wrapper__属性,使其看起来像原始函数。这在创建包装器函数时非常有用。

用法示例
from functools import update_wrapper
 
def my_decorator(f):
    def wrapper(*args, **kwargs):
        return f(*args, **kwargs) + 1
    update_wrapper(wrapper, f)
    return wrapper
 
@my_decorator
def increment(n):
    return n
 
print(increment.__name__)  # 输出: increment


8. partialmethod

partialmethodfunctools 模块中的一个类装饰器,它允许你创建一个绑定了固定参数的方法,类似于 partial 函数,但是用于方法而不是函数。

用法示例
from functools import partialmethod
 
class MyClass:
    def method(self, arg1, arg2):
        return arg1 + arg2
 
    @partialmethod
    def static_method(self, arg1):
        return static_method(arg1, 2)
 
instance = MyClass()
print(instance.static_method(10))  # 输出: 12

9. singledispatchmethod

singledispatchmethod 是一个类装饰器,它允许你为类中的方法实现单分派通用方法。与 singledispatch 类似,但它是用于类方法的。

用法示例
from functools import singledispatchmethod
 
class MyClass:
    @singledispatchmethod
    def method(self, arg):
        return f"No implementation for {type(arg)}"
 
    @method.register(int)
    def _(self, arg):
        return f"The integer is {arg}"
 
    def method(self, arg):
        return super().method(arg)
 
instance = MyClass()
print(instance.method(42))  # 输出: The integer is 42

10. cache

cachefunctools 模块中的一个类装饰器,它类似于 lru_cache,但提供了更少的保证和更低的开销。它用于缓存函数的结果,但没有最大缓存大小的限制。

用法示例
from functools import cache
 
@cache
def fibonacci(n):
    if n < 2:
        return n
    return fibonacci(n - 1) + fibonacci(n - 2)
 
print(fibonacci(10))  # 输出: 55

11. total_ordering

total_ordering 是一个类装饰器,用于自动为类生成比较方法。当你定义了一个类并且实现了它的 __eq__ 方法时,total_ordering 可以确保类的行为符合预期。

用法示例
from functools import total_ordering
 
@total_ordering
class MyClass:
    def __init__(self, value):
        self.value = value
 
    def __eq__(self, other):
        return self.value == other.value
 
    def __repr__(self):
        return f"MyClass({self.value!r})"
 
instance1 = MyClass(1)
instance2 = MyClass(1)
instance3 = MyClass(2)
 
print(instance1 < instance2)  # 输出: False
print(instance1 < instance3)  # 输出: True

12. wraps

wraps 是一个装饰器,用于包装函数。它用于保持被包装函数的元数据(如名称、文档字符串和注解)不变。

用法示例
from functools import wraps
 
def my_decorator(f):
    @wraps(f)
    def wrapper(*args, **kwargs):
        return f(*args, **kwargs) + 1
    return wrapper
 
@my_decorator
def increment(n):
    return n
 
print(increment.__name__)  # 输出: increment
print(increment.__doc__)  # 输出函数的文档字符串

13. singledispatch

singledispatch 是一个多分派通用装饰器,它允许你根据传递给函数的第一个参数的类型来分派到不同的实现。

用法示例
from functools import singledispatch
 
@singledispatch
def process(value):
    return f"Unknown type: {type(value)}"
 
@process.register(str)
def _(value):
    return f"String: {value}"
 
@process.register(int)
def _(value):
    return f"Integer: {value}"
 
print(process("hello"))  # 输出: String: hello
print(process(42))     # 输出: Integer: 42

1bf3b0890855479297287898c90bc679.png

完。

目录
相关文章
|
1天前
|
缓存 算法 数据处理
Python入门:9.递归函数和高阶函数
在 Python 编程中,函数是核心组成部分之一。递归函数和高阶函数是 Python 中两个非常重要的特性。递归函数帮助我们以更直观的方式处理重复性问题,而高阶函数通过函数作为参数或返回值,为代码增添了极大的灵活性和优雅性。无论是实现复杂的算法还是处理数据流,这些工具都在开发者的工具箱中扮演着重要角色。本文将从概念入手,逐步带你掌握递归函数、匿名函数(lambda)以及高阶函数的核心要领和应用技巧。
Python入门:9.递归函数和高阶函数
|
4天前
|
数据采集 JavaScript Android开发
【02】仿站技术之python技术,看完学会再也不用去购买收费工具了-本次找了小影-感觉页面很好看-本次是爬取vue需要用到Puppeteer库用node.js扒一个app下载落地页-包括安卓android下载(简单)-ios苹果plist下载(稍微麻烦一丢丢)-优雅草卓伊凡
【02】仿站技术之python技术,看完学会再也不用去购买收费工具了-本次找了小影-感觉页面很好看-本次是爬取vue需要用到Puppeteer库用node.js扒一个app下载落地页-包括安卓android下载(简单)-ios苹果plist下载(稍微麻烦一丢丢)-优雅草卓伊凡
29 7
【02】仿站技术之python技术,看完学会再也不用去购买收费工具了-本次找了小影-感觉页面很好看-本次是爬取vue需要用到Puppeteer库用node.js扒一个app下载落地页-包括安卓android下载(简单)-ios苹果plist下载(稍微麻烦一丢丢)-优雅草卓伊凡
|
28天前
|
测试技术 Python
【03】做一个精美的打飞机小游戏,规划游戏项目目录-分门别类所有的资源-库-类-逻辑-打包为可玩的exe-练习python打包为可执行exe-优雅草卓伊凡-持续更新-分享源代码和游戏包供游玩-1.0.2版本
【03】做一个精美的打飞机小游戏,规划游戏项目目录-分门别类所有的资源-库-类-逻辑-打包为可玩的exe-练习python打包为可执行exe-优雅草卓伊凡-持续更新-分享源代码和游戏包供游玩-1.0.2版本
106 31
【03】做一个精美的打飞机小游戏,规划游戏项目目录-分门别类所有的资源-库-类-逻辑-打包为可玩的exe-练习python打包为可执行exe-优雅草卓伊凡-持续更新-分享源代码和游戏包供游玩-1.0.2版本
|
1月前
|
机器学习/深度学习 存储 数据挖掘
Python图像处理实用指南:PIL库的多样化应用
本文介绍Python中PIL库在图像处理中的多样化应用,涵盖裁剪、调整大小、旋转、模糊、锐化、亮度和对比度调整、翻转、压缩及添加滤镜等操作。通过具体代码示例,展示如何轻松实现这些功能,帮助读者掌握高效图像处理技术,适用于图片美化、数据分析及机器学习等领域。
73 20
|
2月前
|
XML JSON 数据库
Python的标准库
Python的标准库
185 77
|
2月前
|
XML JSON 数据库
Python的标准库
Python的标准库
71 11
|
2月前
|
数据可视化 Python
以下是一些常用的图表类型及其Python代码示例,使用Matplotlib和Seaborn库。
通过这些思维导图和分析说明表,您可以更直观地理解和选择适合的数据可视化图表类型,帮助更有效地展示和分析数据。
105 8
|
2月前
|
安全 API 文件存储
Yagmail邮件发送库:如何用Python实现自动化邮件营销?
本文详细介绍了如何使用Yagmail库实现自动化邮件营销。Yagmail是一个简洁强大的Python库,能简化邮件发送流程,支持文本、HTML邮件及附件发送,适用于数字营销场景。文章涵盖了Yagmail的基本使用、高级功能、案例分析及最佳实践,帮助读者轻松上手。
88 4
|
3月前
|
人工智能 API 开发工具
aisuite:吴恩达发布开源Python库,一个接口调用多个大模型
吴恩达发布的开源Python库aisuite,提供了一个统一的接口来调用多个大型语言模型(LLM)服务。支持包括OpenAI、Anthropic、Azure等在内的11个模型平台,简化了多模型管理和测试的工作,促进了人工智能技术的应用和发展。
226 1
aisuite:吴恩达发布开源Python库,一个接口调用多个大模型
|
3月前
|
机器学习/深度学习 算法 数据挖掘
数据分析的 10 个最佳 Python 库
数据分析的 10 个最佳 Python 库
198 4
数据分析的 10 个最佳 Python 库

热门文章

最新文章

推荐镜像

更多