Python functools模块学习总结


Posted in Python onMay 09, 2015

文档 地址

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__']
Python 相关文章推荐
Python读取mp3中ID3信息的方法
Mar 05 Python
Python易忽视知识点小结
May 25 Python
python实现井字棋游戏
Mar 30 Python
详解Python pygame安装过程笔记
Jun 05 Python
详解如何使用Python编写vim插件
Nov 28 Python
Python cookbook(数据结构与算法)对切片命名清除索引的方法
Mar 13 Python
Python实现的旋转数组功能算法示例
Feb 23 Python
从多个tfrecord文件中无限读取文件的例子
Feb 17 Python
使用python求斐波那契数列中第n个数的值示例代码
Jul 26 Python
Python操作word文档插入图片和表格的实例演示
Oct 25 Python
Pytorch 中的optimizer使用说明
Mar 03 Python
用基于python的appium爬取b站直播消费记录
Apr 17 Python
Python浅拷贝与深拷贝用法实例
May 09 #Python
九步学会Python装饰器
May 09 #Python
Python类属性与实例属性用法分析
May 09 #Python
python回调函数用法实例分析
May 09 #Python
python类和函数中使用静态变量的方法
May 09 #Python
Python实用日期时间处理方法汇总
May 09 #Python
python fabric使用笔记
May 09 #Python
You might like
高分R级DC动画剧《哈莉·奎茵》第二季正式预告首发
2020/04/09 欧美动漫
PHP 5昨天隆重推出--PHP 5/Zend Engine 2.0新特性
2006/10/09 PHP
PHP4与PHP3中一个不兼容问题的解决方法
2006/10/09 PHP
php中用于检测一个地理IP地址是否可用的代码
2012/02/19 PHP
Yii安装与使用Excel扩展的方法
2016/07/13 PHP
PHP从零开始打造自己的MVC框架之入口文件实现方法详解
2019/06/03 PHP
javascript 一些用法小结
2009/09/11 Javascript
js中的前绑定和后绑定详解
2013/08/01 Javascript
js中点击空白区域时文本框与隐藏层的显示与影藏问题
2013/08/26 Javascript
javascript:void(0)的作用示例介绍
2013/10/28 Javascript
js统计录入文本框中字符的个数并加以限制不超过多少
2014/05/23 Javascript
中文输入法不触发onkeyup事件的解决办法
2014/07/09 Javascript
利用CSS、JavaScript及Ajax实现图片预加载的方法
2016/11/29 Javascript
Html5+jQuery+CSS制作相册小记录
2016/12/30 Javascript
关于AngularJs数据的本地存储详解
2017/01/20 Javascript
js使用formData实现批量上传
2020/03/27 Javascript
微信小程序实现页面分享onShareAppMessage
2019/08/12 Javascript
js实现电灯开关效果
2021/01/19 Javascript
精确查找PHP WEBSHELL木马的方法(1)
2011/04/12 Python
python3实现字符串操作的实例代码
2019/04/16 Python
Django结合ajax进行页面实时更新的例子
2019/08/12 Python
Pycharm编辑器功能之代码折叠效果的实现代码
2020/10/15 Python
详解html5 shiv.js和respond.min.js
2018/01/24 HTML / CSS
美国机场停车位预订:About Airport Parking
2018/03/26 全球购物
Jones New York官网:美国女装品牌,受白领女性欢迎
2019/11/26 全球购物
伊莱克斯阿根廷网上商店:Tienda Electrolux
2021/03/08 全球购物
C语言基础笔试题
2013/04/27 面试题
党员领导干部廉洁从政承诺书
2014/03/27 职场文书
体育馆的标语
2014/06/24 职场文书
光学与应用专业毕业生求职信
2014/09/01 职场文书
开展批评与自我批评心得体会
2014/10/17 职场文书
出差报告范文
2014/11/06 职场文书
校长个人总结
2015/03/03 职场文书
个人简历求职信范文
2015/03/20 职场文书
2015年工商局个人工作总结
2015/07/23 职场文书
Java Dubbo框架知识点梳理
2021/06/26 Java/Android