Python的functools模块

本文介绍了Python标准库中的functools模块,该模块提供了一系列的功能来增强函数的能力,包括偏函数、装饰器、缓存机制及单分发器等高级特性。适合希望了解如何利用这些工具提高代码效率和可读性的开发者。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

Python的functools模块
functools 模块可以说主要是为函数式编程而设计,用于增强函数功能。
functools模块用以为可调用对象(callable objects)定义高阶函数或操作。

文章目录
Python的functools模块
partial
update_wrapper
wraps
reduce
cmp_to_key
lru_cache
singledispatch
partial
用于创建一个偏函数,将默认参数包装一个可调用对象,返回结果也是可调用对象。
偏函数可以固定住原函数的部分参数,从而在调用时更简单。

from functools import partial

int2 = partial(int, base=8)
print(int2('123'))
# 83
1
2
3
4
5
update_wrapper
使用 partial 包装的函数是没有__name__和__doc__属性的。
update_wrapper 作用:将被包装函数的__name__等属性,拷贝到新的函数中去。

from functools import update_wrapper
def wrap2(func):
    def inner(*args):
        return func(*args)
    return update_wrapper(inner, func)

@wrap2
def demo():
    print('hello world')

print(demo.__name__)
# demo
1
2
3
4
5
6
7
8
9
10
11
12
wraps
warps 函数是为了在装饰器拷贝被装饰函数的__name__。
就是在update_wrapper上进行一个包装

from functools import wraps
def wrap1(func):
    @wraps(func)    # 去掉就会返回inner
    def inner(*args):
        print(func.__name__)
        return func(*args)
    return inner

@wrap1
def demo():
    print('hello world')

print(demo.__name__)
# demo
1
2
3
4
5
6
7
8
9
10
11
12
13
14
reduce
在 Python2 中等同于内建函数 reduce
函数的作用是将一个序列归纳为一个输出
reduce(function, sequence, startValue)

from functools import reduce

l = range(1,50)
print(reduce(lambda x,y:x+y, l))
# 1225
1
2
3
4
5
cmp_to_key
在 list.sort 和 内建函数 sorted 中都有一个 key 参数

x = ['hello','worl','ni']
x.sort(key=len)
print(x)
# ['ni', 'worl', 'hello']
1
2
3
4
Python3 之前还提供了cmp参数来比较两个元素
cmp_to_key 函数就是用来将老式的比较函数转化为 key 函数
lru_cache
允许我们将一个函数的返回值快速地缓存或取消缓存。
该装饰器用于缓存函数的调用结果,对于需要多次调用的函数,而且每次调用参数都相同,则可以用该装饰器缓存调用结果,从而加快程序运行。
该装饰器会将不同的调用结果缓存在内存中,因此需要注意内存占用问题。

from functools import lru_cache
@lru_cache(maxsize=30)  # maxsize参数告诉lru_cache缓存最近多少个返回值
def fib(n):
    if n < 2:
        return n
    return fib(n-1) + fib(n-2)
print([fib(n) for n in range(10)])
fib.cache_clear()   # 清空缓存
1
2
3
4
5
6
7
8
singledispatch
单分发器, Python3.4新增,用于实现泛型函数。
根据单一参数的类型来判断调用哪个函数。

from functools import singledispatch
@singledispatch
def fun(text):
    print('String:' + text)

@fun.register(int)
def _(text):
    print(text)

@fun.register(list)
def _(text):
    for k, v in enumerate(text):
        print(k, v)

@fun.register(float)
@fun.register(tuple)
def _(text):
    print('float, tuple')
fun('i am is hubo')
fun(123)
fun(['a','b','c'])
fun(1.23)
print(fun.registry)    # 所有的泛型函数
print(fun.registry[int])    # 获取int的泛型函数
# String:i am is hubo
# 123
# 0 a
# 1 b
# 2 c
# float, tuple
# {<class 'object'>: <function fun at 0x106d10f28>, <class 'int'>: <function _ at 0x106f0b9d8>, <class 'list'>: <function _ at 0x106f0ba60>, <class 'tuple'>: <function _ at 0x106f0bb70>, <class 'float'>: <function _ at 0x106f0bb70>}
# <function _ at 0x106f0b9d8>
 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值