Python functools模块学习总结
作者:junjie 发布时间:2023-09-22 07:21:54
文档 地址
functools.partial
作用:
functools.partial 通过包装手法,允许我们 "重新定义" 函数签名
用一些默认参数包装一个可调用对象,返回结果是可调用对象,并且可以像原始对象一样对待
冻结部分函数位置函数或关键字参数,简化函数,更少更灵活的函数参数调用
#args/keywords 调用partial时参数
def partial(func, *args, **keywords):
def newfunc(*fargs, **fkeywords):
newkeywords = keywords.copy()
newkeywords.update(fkeywords)
return func(*(args + fargs), **newkeywords) #合并,调用原始函数,此时用了partial的参数
newfunc.func = func
newfunc.args = args
newfunc.keywords = keywords
return newfunc
声明:
urlunquote = functools.partial(urlunquote, encoding='latin1')
当调用 urlunquote(args, *kargs)
相当于 urlunquote(args, *kargs, encoding='latin1')
E.g:
import functools
def add(a, b):
return a + b
add(4, 2)
6
plus3 = functools.partial(add, 3)
plus5 = functools.partial(add, 5)
plus3(4)
7
plus3(7)
10
plus5(10)
15
应用:
典型的,函数在执行时,要带上所有必要的参数进行调用。
然后,有时参数可以在函数被调用之前提前获知。
这种情况下,一个函数有一个或多个参数预先就能用上,以便函数能用更少的参数进行调用。
functool.update_wrapper
默认partial对象没有__name__和__doc__, 这种情况下,对于装饰器函数非常难以debug.使用update_wrapper(),从原始对象拷贝或加入现有partial对象
它可以把被封装函数的__name__、module、__doc__和 __dict__都复制到封装函数去(模块级别常量WRAPPER_ASSIGNMENTS, WRAPPER_UPDATES)
>>> functools.WRAPPER_ASSIGNMENTS
('__module__', '__name__', '__doc__')
>>> functools.WRAPPER_UPDATES
('__dict__',)
这个函数主要用在装饰器函数中,装饰器返回函数反射得到的是包装函数的函数定义而不是原始函数定义
#!/usr/bin/env python
# encoding: utf-8
def wrap(func):
def call_it(*args, **kwargs):
"""wrap func: call_it"""
print 'before call'
return func(*args, **kwargs)
return call_it
@wrap
def hello():
"""say hello"""
print 'hello world'
from functools import update_wrapper
def wrap2(func):
def call_it(*args, **kwargs):
"""wrap func: call_it2"""
print 'before call'
return func(*args, **kwargs)
return update_wrapper(call_it, func)
@wrap2
def hello2():
"""test hello"""
print 'hello world2'
if __name__ == '__main__':
hello()
print hello.__name__
print hello.__doc__
print
hello2()
print hello2.__name__
print hello2.__doc__
得到结果:
before call
hello world
call_it
wrap func: call_it
before call
hello world2
hello2
test hello
functool.wraps
调用函数装饰器partial(update_wrapper, wrapped=wrapped, assigned=assigned, updated=updated)的简写
from functools import wraps
def wrap3(func):
@wraps(func)
def call_it(*args, **kwargs):
"""wrap func: call_it2"""
print 'before call'
return func(*args, **kwargs)
return call_it
@wrap3
def hello3():
"""test hello 3"""
print 'hello world3'
结果
before call
hello world3
hello3
test hello 3
functools.reduce
functools.reduce(function, iterable[, initializer])
等同于内置函数reduce()
用这个的原因是使代码更兼容(python3)
functools.cmp_to_key
functools.cmp_to_key(func)
将老式鼻尖函数转换成key函数,用在接受key函数的方法中(such as sorted(), min(), max(), heapq.nlargest(), heapq.nsmallest(), itertools.groupby())
一个比较函数,接收两个参数,小于,返回负数,等于,返回0,大于返回整数
key函数,接收一个参数,返回一个表明该参数在期望序列中的位置
例如:
sorted(iterable, key=cmp_to_key(locale.strcoll)) # locale-aware sort order
functools.total_ordering
functools.total_ordering(cls)
这个装饰器是在python2.7的时候加上的,它是针对某个类如果定义了__lt__、le、gt、__ge__这些方法中的至少一个,使用该装饰器,则会自动的把其他几个比较函数也实现在该类中
@total_ordering
class Student:
def __eq__(self, other):
return ((self.lastname.lower(), self.firstname.lower()) ==
(other.lastname.lower(), other.firstname.lower()))
def __lt__(self, other):
return ((self.lastname.lower(), self.firstname.lower()) <
(other.lastname.lower(), other.firstname.lower()))
print dir(Student)
得到
['__doc__', '__eq__', '__ge__', '__gt__', '__le__', '__lt__', '__module__']


猜你喜欢
- 今天搭了个“发短信”的页面,找朋友测试,没想到一位大侠直接弄了本长篇小说发我手机上……为了我的宝贝手机能继续健康澎湃,给文本区域(texta
- 1、缘由在日常开发中,我们经常需要监控应用程序的状态,及时发现问题并采取措施解决。而通过邮件发送报警信息则是一种常见的实现方式。Python
- 该模块主要功能是提供可存储cookie的对象。使用此模块捕获cookie并在后续连接请求时重新发送,还可以用来处理包含cookie数据的文件
- 本文实例为大家分享了js实现页面图片消除的具体代码,供大家参考,具体内容如下前两天测试的时候发现自己对js还不是太熟悉,所以今天上传的了这篇
- 这两天一直在做课件,我个人一直不太喜欢PPT这个东西……能不用就不用,我个人特别崇尚极简风。谁让我们是程序员呢,所以就爱上了Jupyter写
- 如下所示:import cv2#循环灰度图片并保存def grayImg(): for x in range(1,38): #读
- 1、epochKeras官方文档中给出的解释是:“简单说,epochs指的就是训练过程接中数据将被“轮”多少次”(1)释义:训练过程中当一个
- 本文实例讲述了Python实现队列的方法。分享给大家供大家参考,具体如下:Python实现队列队列(FIFO),添加元素在队列尾,删除元素在
- 格式化字符串漏洞覆盖大数字时,如果选择一次性输出大数字个字节来进行覆盖,会很久很久,或者直接报错中断,所以来搞个攻防世界高手区的题目来总结一
- 本文给大家介绍Python文件处理相关知识,具体内容如下所示:1.文件的常见操作文件是日常编程中常用的操作,通常用于存储数据或应用系统的参数
- Beautiful Soup就是Python的一个HTML或XML的解析库,可以用它来方便地从网页中提取数据。它有如下三个特点:Beauti
- 有时候我们会在页面上显示用户的所在地区,这个原理是:先得到用户的IP,然后去查询将IP转换成一个数值,最后去查这个数值所在的范围,来得到用户
- 目录注册组件添加组件源代码可拖放文本框允许用户通过拖动备选项至文本框来确定输入,其实也可以说是 combobox 的一种变形。 与 comb
- 前言数组类型是各种编程语言中基本的数组结构了,本文来盘点下Python中各种“数组”类型的实现。listtuplearray.arrayst
- 日志文件一般是按天产生,则通过在程序中判断文件的产生日期与当前时间,更换监控的日志文件程序只是简单的示例一下,监控test1.log 10秒
- eval 跟json.loads 是不一样的函数,是有实现不一样功能的地方,但是在某些地方它们两个函数的功能是一样的,在这个时候如果对执行效
- 如下所示:import cv2import mathimport numpy as npdef move(img): height, wid
- NumPy什么是NumPyNumPy是 Python 语言的一个扩展程序库,支持大量的维度数组与矩阵运算,此外也针对数组运算提供大量的数学函
- 在程序中,有多种方法进行强制类型转换。本博文将介绍一个非常常用的方法:to()方法。我们通常使用它来进行GPU和CPU的类型转换,但其实也可
- 在Python中,当我们有两个字典需要合并的时候,可以使用字典的 update 方法,例如:a = {'a': 1,