Python中functools模块函数解析
Python自带的 functools 模块提供了一些常用的高阶函数,也就是用于处理其它函数的特殊函数。换言之,就是能使用该模块对可调用对象进行处理。
functools模块函数概览
- functools.cmp_to_key(func)
- functools.total_ordering(cls)
- functools.reduce(function, iterable[, initializer])
- functools.partial(func[, args][, *keywords])
- functools.update_wrapper(wrapper, wrapped[, assigned][, updated])
- functools.wraps(wrapped[, assigned][, updated])
functools.cmp_to_key()
语法:
functools.cmp_to_key(func)
该函数用于将旧式的比较函数转换为关键字函数。
旧式的比较函数:接收两个参数,返回比较的结果。返回值小于零则前者小于后者,返回值大于零则相反,返回值等于零则两者相等。
关键字函数:接收一个参数,返回其对应的可比较对象。例如 sorted(), min(), max(), heapq.nlargest(), heapq.nsmallest(), itertools.groupby() 都可作为关键字函数。
在 Python 3 中,有很多地方都不再支持旧式的比较函数,此时可以使用 cmp_to_key() 进行转换。
示例:
sorted(iterable, key=cmp_to_key(cmp_func))
functools.total_ordering()
语法:
functools.total_ordering(cls)
这是一个类装饰器,用于自动实现类的比较运算。
我们只需要在类中实现 __eq__() 方法和以下方法中的任意一个 __lt__(), __le__(), __gt__(), __ge__(),那么 total_ordering() 就能自动帮我们实现余下的几种比较运算。
示例:
@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()))
functools.reduce()
语法:
functools.reduce(function, iterable[, initializer])
该函数与 Python 内置的 reduce() 函数相同,主要用于编写兼容 Python 3 的代码。
functools.partial()
语法:
functools.partial(func[, *args][, **keywords])
该函数返回一个 partial 对象,调用该对象的效果相当于调用 func 函数,并传入位置参数 args 和关键字参数 keywords 。如果调用该对象时传入了位置参数,则这些参数会被添加到 args 中。如果传入了关键字参数,则会被添加到 keywords 中。
partial() 函数的等价实现大致如下:
def partial(func, *args, **keywords): def newfunc(*fargs, **fkeywords):newkeywords = keywords.copy()newkeywords.update(fkeywords)return func(*(args + fargs), **newkeywords)newfunc.func = funcnewfunc.args = argsnewfunc.keywords = keywordsreturn newfunc
partial() 函数主要用于“冻结”某个函数的部分参数,返回一个参数更少、使用更简单的函数对象。
示例:
>>> from functools import partial >>> basetwo = partial(int, base=2) >>> basetwo.__doc__ = 'Convert base 2 string to an int.' >>> basetwo('10010') 18
functools.update_wrapper()
语法:
functools.update_wrapper(wrapper, wrapped[, assigned][, updated])
该函数用于更新包装函数(wrapper),使它看起来像原函数一样。可选的参数是一个元组,assigned 元组指定要直接使用原函数的值进行替换的属性,updated 元组指定要对照原函数进行更新的属性。这两个参数的默认值分别是模块级别的常量:WRAPPER_ASSIGNMENTS 和 WRAPPER_UPDATES。前者指定了对包装函数的 __name__, __module__, __doc__ 属性进行直接赋值,而后者指定了对包装函数的 __dict__ 属性进行更新。
该函数主要用于装饰器函数的定义中,置于包装函数之前。如果没有对包装函数进行更新,那么被装饰后的函数所具有的元信息就会变为包装函数的元信息,而不是原函数的元信息。
functools.wraps()
语法:
functools.wraps(wrapped[, assigned][, updated])
wraps() 简化了 update_wrapper() 函数的调用。它等价于 partial(update_wrapper, wrapped=wrapped, assigned, updated=updated)。
示例:
>>> from functools import wraps >>> def my_decorator(f): ... @wraps(f) ... def wrapper(*args, **kwds): ... print 'Calling decorated function' ... return f(*args, **kwds) ... return wrapper>>> @my_decorator ... def example(): ... """Docstring""" ... print 'Called example function'>>> example() Calling decorated function Called example function >>> example.__name__ 'example' >>> example.__doc__ 'Docstring'
如果不使用这个函数,示例中的函数名就会变成 wrapper ,并且原函数 example() 的说明文档(docstring)就会丢失。
转载于:https://www.cnblogs.com/caodneg7/p/10144835.html
Python中functools模块函数解析相关推荐
- python中functools的partiaethod_Python中functools模块函数解析
Python自带的 functools 模块提供了一些常用的高阶函数,也就是用于处理其它函数的特殊函数.换言之,就是能使用该模块对可调用对象进行处理. functools模块函数概览 functool ...
- python跨函数调用变量_对python中不同模块(函数、类、变量)的调用详解
首先,先介绍两种引入模块的方法. 法一:将整个文件引入 import 文件名 文件名.函数名( ) / 文件名.类名 通过这个方法可以运行另外一个文件里的函数 法二:只引入某个文件中一个类/函数/变量 ...
- python中math模块函数_Python常用的一些内建函数和math模块函数
一:Python内建函数 1 #abs取绝对值 2 num = -10 3 print(abs(num))4 5 #max 求最大值 6 print(max(6, 9, 2, 12, 8))7 8 # ...
- Python中第三方模块requests解析
一.简述 Requests HTTP Library 二.模块框架 '''__version___internal_utilsadaptersapiauthcertscompatcookiesexce ...
- python中math模块函数_python中math模块函数
Python Math 函数必须import math 功能说明指令範例返回x 的反余弦math.acos(x) 返回x 的反双曲余弦math.acosh(x) 返回x 的反正弦math.asin(x ...
- python中append函数解析_对python中的pop函数和append函数详解
对python中的pop函数和append函数详解 pop()函数 1.描述 pop() 函数用于移除列表中的一个元素(默认最后一个元素),并且返回该元素的值. 语法 pop()方法语法: list. ...
- 从列表、字符串、元组或集合中随机抽取指定个元素 Python中random模块的sample()函数
选择题 以下python代码的输出结果不可能为? from random import sample s = ['a','b','c','d'] result = sample(s,3) print( ...
- Python中random模块常用函数/方法(2)——random.random(),random.randint()和random.uniform()
1.random.random():生成一个0到1的随机符点数: 0 <= n < 1.0 语法:random.random() #生成一个0~1之间的随机浮点数 print(" ...
- python中的strptime函数_Python中datetime模块中strftime/strptime函数
python中datetime模块非常好用,提供了日期格式和字符串格式相互转化的函数strftime/strptime 1.由日期格式转化为字符串格式的函数为: datetime.datetime.s ...
最新文章
- [svc]arp协议的细枝末节
- flask从服务器获取html页面,flask的ajax、获取服务器数据、放到前端页面、如果数据存在显示标签、如果不存在不显示标签...
- 蓝牙Bluetooth技术小知识
- 荣耀Magic4核心配置曝光:最强驯龙高手 性能远超iPhone 13 Pro
- java中import的使用
- 模拟新浪新闻在线聊天功能
- mysql select大全_Mysql select 大全
- 炮爽2 html5,HTML5入门习作2:炮台
- @Configuration与@Component作为配置类的区别
- Oracle数据库内存使用情况分析查看
- java希尔密码,希尔
- php 检查货币类型_PHP如何获取货币汇率-百度经验
- 停止dockerd进程
- 常见服务器故障有哪些?如何预防服务器发生故障?服务器故障后如何恢复数据?
- 巧用Q盘搭建SVN服务器
- 华硕linux网卡驱动,华硕官网主板型号”P5BV-C”的Linux的网卡驱动加载
- drcom for linux,Ubuntu Linux 6.10下用Dr.COM(drcom-client)接入网络的问题
- 十六进制配色(ggplot2配色)
- pep8 python 编码规范下载_PEP8 Python 编码规范整理
- 【数据分析与挖掘】数据分析学习及实践记录 | part 03-matplotlib常用统计图
热门文章
- solution: stuch on 'setting up your MAC'
- 验证码颜色、字母、数字、线条、圆点、位置都随机,点击切换验证码
- Log--日志变大原因总结
- LeetCode-Largest Rectangle in Histogram
- 关于在WinForm里用HttpWebRequest获得某个页面,并填写页面的textbox及点击button的方法...
- Silverlight 2 控件 SDK 源代码
- x == (x = y) 不等于 (x = y) == x ?
- python-爬虫学习(文字、图片、视频)
- [c++基础] const char and static const char
- mysql获取表的行号