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文件夹与文件的操作实现代码
Jul 13 Python
Python的Bottle框架中返回静态文件和JSON对象的方法
Apr 30 Python
Python中利用Scipy包的SIFT方法进行图片识别的实例教程
Jun 03 Python
浅谈python for循环的巧妙运用(迭代、列表生成式)
Sep 26 Python
python在文本开头插入一行的实例
May 02 Python
利用Python读取txt文档的方法讲解
Jun 23 Python
Python2.7环境Flask框架安装简明教程【已测试】
Jul 13 Python
浅析python中的迭代与迭代对象
Oct 08 Python
Python分割训练集和测试集的方法示例
Sep 19 Python
Python面向对象之多态原理与用法案例分析
Dec 30 Python
Python 中的pygame安装与配置教程详解
Feb 10 Python
Lombok插件安装(IDEA)及配置jar包使用详解
Nov 04 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
php面向对象全攻略 (十四) php5接口技术
2009/09/30 PHP
php &amp;&amp; 逻辑与运算符使用说明
2010/03/04 PHP
在PHP中操作Excel实例代码
2010/04/29 PHP
PHP读取并输出XML文件数据的简单实现方法
2017/12/22 PHP
极酷的javascirpt,让你随意编辑任何网页
2007/02/25 Javascript
javascript 闭包
2011/09/15 Javascript
EditPlus注册码生成器(js代码实现)
2013/03/25 Javascript
js/jquery获取文本框输入焦点的方法
2014/03/04 Javascript
JavaScript中的方法调用详细介绍
2014/12/30 Javascript
JavaScript中document.forms[0]与getElementByName区别
2015/01/21 Javascript
jquery解析XML及获取XML节点名称的实现代码
2016/05/18 Javascript
jQuery解决IE6、7、8不能使用 JSON.stringify 函数的问题
2016/05/31 Javascript
jquery自动补齐功能插件flexselect用法示例
2016/08/06 Javascript
100多个基础常用JS函数和语法集合大全
2017/02/16 Javascript
vue.js 双层嵌套for遍历的方法详解, 类似php foreach()
2018/09/07 Javascript
在Vue环境下利用worker运行interval计时器的步骤
2019/08/01 Javascript
微信小程序实现文件预览
2020/10/22 Javascript
vue mvvm数据响应实现
2020/11/11 Javascript
[01:03:41]完美世界DOTA2联赛PWL S3 DLG vs Phoenix 第一场 12.17
2020/12/19 DOTA
使用python开发vim插件及心得分享
2014/11/04 Python
python爬取淘宝商品销量信息
2018/11/16 Python
python实现微信防撤回神器
2019/04/29 Python
pytorch GAN伪造手写体mnist数据集方式
2020/01/10 Python
Matplotlib使用字符串代替变量绘制散点图的方法
2020/02/17 Python
Python实现汇率转换操作
2020/05/03 Python
迪斯尼商品官方网站:ShopDisney
2016/08/01 全球购物
瑞士香水购物网站:Parfumcity.ch
2017/01/14 全球购物
英国顶级珠宝品牌之家:John Greed
2018/06/09 全球购物
优秀学生干部先进事迹材料
2014/05/26 职场文书
六查六看剖析材料
2014/10/06 职场文书
2014年仓库工作总结
2014/11/20 职场文书
服装区域经理岗位职责
2015/04/10 职场文书
物业接待员岗位职责
2015/04/15 职场文书
2015年社区纪检工作总结
2015/04/21 职场文书
新教师教学工作总结
2015/08/12 职场文书
Redis监控工具RedisInsight安装与使用
2022/03/21 Redis