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 相关文章推荐
Python2.5/2.6实用教程 入门基础篇
Nov 29 Python
在Python的Flask框架中实现单元测试的教程
Apr 20 Python
python使用fileinput模块实现逐行读取文件的方法
Apr 29 Python
利用Python抓取行政区划码的方法
Nov 28 Python
TensorFlow实现RNN循环神经网络
Feb 28 Python
基于python进行桶排序与基数排序的总结
May 29 Python
python批量修改文件编码格式的方法
May 31 Python
Django中的文件的上传的几种方式
Jul 23 Python
python中redis查看剩余过期时间及用正则通配符批量删除key的方法
Jul 30 Python
python pyheatmap包绘制热力图
Nov 09 Python
Python HTML解析模块HTMLParser用法分析【爬虫工具】
Apr 05 Python
Python pytesseract验证码识别库用法解析
Jun 29 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
PHPWind与Discuz截取字符函数substrs与cutstr性能比较
2011/12/05 PHP
PHP 获取文件路径(灵活应用__FILE__)
2013/02/15 PHP
JQuery 动画卷页 返回顶部 动画特效(兼容Chrome)
2010/02/15 Javascript
JS实现很酷的水波文字特效实例
2015/02/26 Javascript
jQuery中的on与bind绑定事件区别实例详解
2017/02/28 Javascript
详解Vue.js之视图和数据的双向绑定(v-model)
2017/06/23 Javascript
Javascript调试之console对象——你不知道的一些小技巧
2017/07/10 Javascript
推荐10款扩展Web表单的JS插件
2017/12/25 Javascript
JS实现骰子3D旋转效果
2019/10/24 Javascript
微信小程序实现多图上传
2020/06/19 Javascript
[04:52]第二届DOTA2亚洲邀请赛主赛事第一天比赛集锦:OG娜迦海妖放大配合谜团大中3人
2017/04/02 DOTA
python client使用http post 到server端的代码
2013/02/10 Python
Python实现多行注释的另类方法
2014/08/22 Python
Python numpy 提取矩阵的某一行或某一列的实例
2018/04/03 Python
浅谈Python traceback的优雅处理
2018/08/31 Python
python批量创建指定名称的文件夹
2019/03/21 Python
Python3.7安装PyQt5 运行配置Pycharm的详细教程
2020/10/15 Python
Python用access判断文件是否被占用的实例方法
2020/12/17 Python
详解CSS3中使用gradient实现渐变效果的方法
2015/08/18 HTML / CSS
精伦电子Java笔试题
2013/01/16 面试题
简述Linux文件系统通过i节点把文件的逻辑结构和物理结构转换的工作过程
2016/01/06 面试题
高中毕业生自我鉴定范文
2013/09/26 职场文书
自动化专业职业生涯规划书范文
2014/01/16 职场文书
村长贪污检举信
2014/04/04 职场文书
银行柜员求职自荐书
2014/06/18 职场文书
检查机关党的群众路线个人整改措施
2014/10/04 职场文书
县政府班子个人对照检查材料
2014/10/05 职场文书
思想作风整顿个人剖析材料
2014/10/06 职场文书
二年级语文上册复习计划
2015/01/19 职场文书
项目验收申请报告
2015/05/15 职场文书
幼儿园班级工作总结2015
2015/05/25 职场文书
高考1977观后感
2015/06/04 职场文书
大学学习委员竞选稿
2015/11/20 职场文书
python中的None与NULL用法说明
2021/05/25 Python
Java新手教程之ArrayList的基本使用
2021/06/20 Java/Android
Python Matplotlib绘制等高线图与渐变色扇形图
2022/04/14 Python