本篇文章给大家带来了关于python的相关知识,主要介绍了python的functools模块使用及说明,具有很好的参考价值,下面一起来看一下,希望对大家有帮助。

【相关推荐:Python3视频教程 】
partial
用于创建一个偏函数,将默认参数包装一个可调用对象,返回结果也是可调用对象。
偏函数可以固定住原函数的部分参数,从而在调用时更简单。
from functools import partial
int2 = partial(int, base=8)
print(int2('123'))
# 83
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
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
reduce
在 Python2 中等同于内建函数 reduce
函数的作用是将一个序列归纳为一个输出
让 macOS 自动化像说话一样简单 —— 用代码控制你的 Mac,无需学习 AppleScript 系统要求 macOS 14+ (Sonoma) Python 3.9+ 需要开启:辅助功能 + 屏幕录制权限
reduce(function, sequence, startValue) from functools import reduce l = range(1,50) print(reduce(lambda x,y:x+y, l)) # 1225
cmp_to_key
在 list.sort 和 内建函数 sorted 中都有一个 key 参数
x = ['hello','worl','ni'] x.sort(key=len) print(x) # ['ni', 'worl', 'hello']
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 <h2>singledispatch</h2><p>单分发器, Python3.4新增,用于实现泛型函数。</p><p>根据单一参数的类型来判断调用哪个函数。</p><pre class="brush:py;">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>: <function>, <class>: <function>, <class>: <function>, <class>: <function>, <class>: <function>}
# <function></function></function></class></function></class></function></class></function></class></function></class>
【相关推荐:Python3视频教程 】
Python免费学习笔记(深入):立即使用
在学习笔记中,你将探索 Python 的核心概念和高级技巧!










