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

完。

目录
相关文章
|
5天前
|
Python
以下是一些常用的图表类型及其Python代码示例,使用Matplotlib和Seaborn库。
以下是一些常用的图表类型及其Python代码示例,使用Matplotlib和Seaborn库。
|
5天前
|
SQL 关系型数据库 MySQL
MySQL操作利器——mysql-connector-python库详解
MySQL操作利器——mysql-connector-python库详解
26 0
|
5天前
|
机器学习/深度学习 数据处理 Python
从NumPy到Pandas:轻松转换Python数值库与数据处理利器
从NumPy到Pandas:轻松转换Python数值库与数据处理利器
16 0
|
5天前
|
Linux 开发者 iOS开发
Python中使用Colorama库输出彩色文本
Python中使用Colorama库输出彩色文本
|
3天前
|
数据挖掘 Python
【Python】应用:pyproj地理计算库应用
这篇博客介绍了 `pyproj` 地理计算库的应用,涵盖地理坐标系统转换与地图投影。通过示例代码展示了如何进行经纬度与UTM坐标的互转,并利用 `pyproj.Geod` 计算两点间的距离及方位角,助力地理数据分析。 安装 `pyproj`:`pip install pyproj`。更多内容欢迎关注本博客,一起学习进步! Pancake 🍰 不迷路。😉*★,°*:.☆( ̄▽ ̄)/$:*.°★* 😏
|
5天前
|
Python
Python中正则表达式(re模块)用法详解
Python中正则表达式(re模块)用法详解
13 2
|
5天前
|
Linux Android开发 iOS开发
开源的Python库,用于开发多点触控应用程序
Kivy是一款开源Python库,专为开发多点触控应用设计,支持Android、iOS、Linux、OS X和Windows等平台。本文将指导你使用Kivy创建“Hello World”应用并打包成Android APK。首先通过`pip install kivy`安装Kivy,然后创建并运行一个简单的Python脚本。接着,安装Buildozer并通过`buildozer init`生成配置文件,修改相关设置后,运行`buildozer -v android debug`命令打包应用。完成构建后,你将在`./bin/`目录下找到类似`your-app-debug.apk`的文件。
12 2
|
6天前
|
API Python
使用Python requests库下载文件并设置超时重试机制
使用Python的 `requests`库下载文件时,设置超时参数和实现超时重试机制是确保下载稳定性的有效方法。通过这种方式,可以在面对网络波动或服务器响应延迟的情况下,提高下载任务的成功率。
21 1
|
4天前
|
数据挖掘 API 数据处理
Python 数据分析及预处理常用库
Python自身数据分析功能有限,需借助第三方库增强。常用库包括NumPy、pandas、Matplotlib等。NumPy由Numeric发展而来,提供了多维数组对象及各种API,支持高效的数据处理,如数学、逻辑运算等,常作为其他高级库如pandas和Matplotlib的依赖库。其内置函数处理速度极快,建议优先使用以提升程序效率。
7 0
|
5天前
|
UED Python
Python requests库下载文件时展示进度条的实现方法
以上就是使用Python `requests`库下载文件时展示进度条的一种实现方法,它不仅简洁易懂,而且在实际应用中非常实用。
10 0
下一篇
无影云桌面