python高阶函数functools模块的具体使用
作者:alwaysrun 发布时间:2022-12-08 09:03:15
functools模块提供了一些常用的高阶函数(处理其他可调用对象/函数的特殊函数;以函数作为输入参数,返回也是函数)。
functools模块
functools模块中的高阶函数可基于已有函数定义新的函数:
cmp_to_key,
total_ordering,
reduce,
partial,
update_wrapper
wraps
reduce
reduce(function, iterable[, initializer])对一个可迭代数据集合中的所有数据进行累积。
function:接受两个参数的函数;
sequence:可迭代对象(tuple/list/dict/str);
initial:可选初始值;
# 累加
reduce(lambda x,y:x+y, [1,2,3,4]) # 10
# 逆序字符串
reduce(lambda x,y:y+x, 'abcdefg') # 'gfedcba'
partial/partialmethod
partial用于"冻结"函数的部分参数,返回一个参数更少、使用更简单的函数对象。使用时,只需传入未冻结的参数即可。partialmethod用于处理类方法。
functools.partial(func[, *args][, **keywords])返回一个新的partial对象:
func:一个可调用的对象或函数;
args:要冻结的位置参数;
keywords:要冻结的关键字参数。
def add(a, b, note="add"):
result = a + b
print(f"{note} result: {result}")
return result
add3 = functools.partial(add, 3)
add5 = functools.partial(add, 5, note="partialed")
print(add3(1)) # add result: 4
print(add3(2, note="partial3")) # partial3 result: 5
print(add5(3)) # partialed result: 8
partialmethod用于类中的方法
class Cell(object):
def __init__(self):
self._alive = False
@property
def alive(self):
return self._alive
def set_state(self, state):
self._alive = bool(state)
set_alive = functools.partialmethod(set_state, True)
set_dead = functools.partialmethod(set_state, False)
c = Cell()
print(c.alive) # False
c.set_alive()
print(c.alive) # True
wraps/update_wrapper
functools.update_wrapper(wrapper, wrapped [, assigned] [, updated])更新一个包裹(wrapper)函数,使其看起来更像被包裹(wrapped)的函数(即把 被封装函数的__name__、__module__、__doc__和 __dict__都复制到封装函数去。wraps是通过partial与update_wrapper实现的。
通常,经由被装饰(decorator)的函数会表现为另外一个函数了(函数名、说明等都变为了装饰器的);通过wraps函数可以消除装饰器的这些副作用。
def wrapper_decorator(func):
@functools.wraps(func) # 若是去掉此wraps,则被装饰的函数名称与说明都变为此函数的
def wrapper(*args, **kwargs):
"""doc of decorator"""
print('in wrapper_decorator...')
return func(*args, **kwargs)
return wrapper
@wrapper_decorator
def example():
"""doc of example"""
print('in example function')
example()
# in wrapper_decorator...
# in example function
print(example.__name__, "; ", example.__doc__) # example ; doc of example
singledispatch/singledispatchmethod
singledispatch将普通函数转换为泛型函数,而singledispatchmethod(3.8引入)将类方法转换为泛型函数:
泛型函数:是指由多个函数(针对不同类型的实现)组成的函数,调用时由分派算法决定使用哪个实现;
Single dispatch:一种泛型函数分派形式,基于第一个参数的类型来决定;
dispatch使用:
singledispatch装饰dispatch的基函数base_fun(即,注册object类型);
注册后续分发函数使用装饰器@{base_fun}.register({type}),注册每种需要特殊处理的类型;
分发函数名称无关紧要,_是个不错的选择;
可以叠放多个register装饰器,让同一个函数支持多种类型;
# 缺省匹配类型,注册object类型(与后续注册类型都不匹配时使用)
@functools.singledispatch
def show_dispatch(obj):
print(obj, type(obj), "dispatcher")
# 匹配str字符串
@show_dispatch.register(str)
def _(text):
print(text, type(text), "str")
# 匹配int
@show_dispatch.register(int)
def _(n):
print(n, type(n), "int")
# 匹配元祖或者字典
@show_dispatch.register(tuple)
@show_dispatch.register(dict)
def _(tup_dic):
print(tup_dic, type(tup_dic), "tuple/dict")
### 打印注册的类型:
# dict_keys([<class 'object'>, <class 'str'>, <class 'int'>, <class 'dict'>, <class 'tuple'>])
print(show_dispatch.registry.keys())
show_dispatch(1)
show_dispatch("xx")
show_dispatch([1])
show_dispatch((1, 2, 3))
show_dispatch({"a": "b"})
# 1 <class 'int'> int
# xx <class 'str'> str
# [1] <class 'list'> dispatcher
# (1, 2, 3) <class 'tuple'> tuple/dict
# {'a': 'b'} <class 'dict'> tuple/dict
cmp_to_key
cmp_to_key()用来自定义排序规则,可将比较函数(comparison function)转化为关键字函数(key function):
比较函数:接受两个参数,比较这两个参数,并返回0、1或-1;
关键字函数:接受一个参数,返回其对应的可比较对象;
test = [1, 3, 5, 2, 4]
test.sort(key=functools.cmp_to_key(lambda x, y: 1 if x < y else -1))
print(test) # [5, 4, 3, 2, 1]
total_ordering
是一个类装饰器,用于自动实现类的比较运算;类定义一个或者多个比较排序方法,类装饰器将会补充其余的比较方法。
被修饰的类必须至少定义 __lt__(), __le__(),__gt__(),__ge__()中的一个,以及__eq__()方法。
如,只需定义lt与eq方法,即可实现所有比较:
@functools.total_ordering
class Person:
def __init__(self, name, age):
self.name = name
self.age = age
def __lt__(self, other):
if isinstance(other, Person):
return self.age < other.age
else:
raise AttributeError("Incorrect attribute!")
def __eq__(self, other):
if isinstance(other, Person):
return self.age == other.age
else:
raise AttributeError("Incorrect attribute!")
mike = Person("mike", 20)
tom = Person("tom", 10)
print(mike < tom)
print(mike <= tom)
print(mike > tom)
print(mike >= tom)
print(mike == tom)
来源:https://blog.csdn.net/alwaysrun/article/details/129767090


猜你喜欢
- 本文实例讲述了Python常见数据结构之栈与队列用法。分享给大家供大家参考,具体如下:Python常见数据结构之-栈首先,栈是一种数据结构。
- 1.筛选出目标值所在行 单列筛选# df[列名].isin([目标值])对当前列中存在目标值的行会返回True,不存在的返回Fal
- 使用Keras如果要使用大规模数据集对网络进行训练,就没办法先加载进内存再从内存直接传到显存了,除了使用Sequence类以外,还可以使用迭
- 0. 学习目标在诸如单链表、双线链表等普通链表中,查找、插入和删除操作由于必须从头结点遍历链表才能找到相关链表,因此时间复杂度均为O(n)。
- 数组都是从0开始。javascript是arrayname[i],而vbscript是arrayname(i) javascript的字符串
- 一、日期类型:对于SQL Server 2008 来说(因为2000甚至2005已经稍微有被淘汰的迹象,所以在此不作过多说明,加上自己工作使
- 模态框Bootstrap ModalBootstrap 的模态框使用Bootstrap 的前端应该都接触过。本文记录一下今天使用时遇到的 B
- 动态生成的IFRAME,设置SRC时的,不同位置带来的影响。以下所说的是在IE7下运行的。IE6下也是同样。在这个blog中,直接点击运行代
- 1、打印九九乘法表#只打印结果for i in range(1,10): for j in range(1,i+1): &nbs
- 如何将产生的密码记录并发送给用户?这里使用了cdonts邮件组件来发送邮件,前提服务器得支持cdonts组件。好了,看看具体实现方法吧,不是
- 示例标准线程多进程,生产者/消费者示例:Worker越多,问题越大# -*- coding: utf8 -*-import osimport
- 众所周知,升级某个库(假设为 xxx),可以用pip install --upgrade xxx 命令,或者简写成pip install -
- 我们知道,Diango 接收的 HTTP 请求信息里带有 Cookie 信息。Cookie的作用是为了识别当前用户的身份,通过以下例子来说明
- 一:Zmail的优势:1:自动填充大多数导致服务端拒信的头信息(From To LocalHost之类的)2:将一个字典映射为email,构
- python这样注释,让你的代码看起来更加的优雅,是不是常常感觉自己的python代码写出来,看起来特别的乱,虽然可以正常运行,但是在优雅性
- <?phphighlight_file(__FILE__);error_reporting(0);$content = $_POST[
- 实验环境 Pytorch 1.7.0torchvision 0.8.2Python 3.8CUDA10.2 + cuDNN v7.
- 如图所示,要处理的数据是一个json数组,而且非常大下图为电脑配置,使用 json.load() 方法加载上述json文件电脑直接卡死解决思
- 前言有的时候我们需要根据不同的用户身份生成不同的路由规则,例如:vip用户应该有自己的vip页面所对应的专用路由。一、初始化项目初始化vit
- 回顾一下已经了解的数据类型:int/str/bool/list/dict/tuple还真的不少了.不过,python是一个发展的语言,没准以