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中的算数运算符的用法
May 13 Python
Python批量重命名同一文件夹下文件的方法
May 25 Python
python计算文本文件行数的方法
Jul 06 Python
Django学习笔记之Class-Based-View
Feb 15 Python
Python3用tkinter和PIL实现看图工具
Jun 21 Python
用python一行代码得到数组中某个元素的个数方法
Jan 28 Python
python 实现selenium断言和验证的方法
Feb 13 Python
pyqt5 获取显示器的分辨率的方法
Jun 18 Python
python根据多个文件名批量查找文件
Aug 13 Python
python numpy数组中的复制知识解析
Feb 03 Python
如何用python处理excel表格
Jun 09 Python
给numpy.array增加维度的超简单方法
Jun 02 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
留言板翻页的实现详解
2006/10/09 PHP
解决ajax+php中文乱码的方法详解
2013/06/09 PHP
jquery each()源代码
2011/02/14 Javascript
基于jquery的3d效果实现代码
2011/03/23 Javascript
javascript解析xml实现省市县三级联动的方法
2015/07/25 Javascript
C++中的string类的用法小结
2015/08/07 Javascript
基于jQuery Bar Indicator 插件实现进度条展示效果
2015/09/30 Javascript
使用jquery插件qrcode生成二维码
2015/10/22 Javascript
Javascript中的几种继承方式对比分析
2016/03/22 Javascript
浅谈JavaScript中的this指针和引用知识
2016/08/05 Javascript
JSON 必知必会 观后记
2016/10/27 Javascript
Angularjs修改密码的实例代码
2017/05/26 Javascript
Webpack的dll功能使用
2018/06/28 Javascript
nodejs中实现修改用户路由功能
2019/05/24 NodeJs
JQuery常用简单动画操作方法回顾与总结
2019/12/07 jQuery
JavaScript中的惰性载入函数及优势
2020/02/18 Javascript
基于JavaScript或jQuery实现网站夜间/高亮模式
2020/05/30 jQuery
python 查找文件夹下所有文件 实现代码
2009/07/01 Python
在python的WEB框架Flask中使用多个配置文件的解决方法
2014/04/18 Python
Python基于Floyd算法求解最短路径距离问题实例详解
2018/05/16 Python
TensorFlow 滑动平均的示例代码
2018/06/19 Python
Python HTML解析器BeautifulSoup用法实例详解【爬虫解析器】
2019/04/05 Python
matlab 计算灰度图像的一阶矩,二阶矩,三阶矩实例
2020/04/22 Python
使用Python3 poplib模块删除服务器多天前的邮件实现代码
2020/04/24 Python
scrapy爬虫:scrapy.FormRequest中formdata参数详解
2020/04/30 Python
Python Opencv实现单目标检测的示例代码
2020/09/08 Python
PyChon中关于Jekins的详细安装(推荐)
2020/12/28 Python
HTML5实现多张图片上传功能
2016/03/11 HTML / CSS
River Island美国官网:英国高街时尚品牌
2018/09/04 全球购物
兰蔻俄罗斯官方网站:Lancome俄罗斯
2019/12/09 全球购物
原材料检验岗位职责
2014/03/15 职场文书
司法建议书范文
2014/05/13 职场文书
北大自主招生自荐信
2015/03/04 职场文书
2016年校园重阳节广播稿
2015/12/18 职场文书
jQuery实现影院选座订座效果
2021/04/13 jQuery
C#连接ORACLE出现乱码问题的解决方法
2021/10/05 Oracle