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通过urllib2爬网页上种子下载示例
Feb 24 Python
tensorflow saver 保存和恢复指定 tensor的实例讲解
Jul 26 Python
Python使用requests提交HTTP表单的方法
Dec 26 Python
python暴力解压rar加密文件过程详解
Jul 05 Python
用python3 urllib破解有道翻译反爬虫机制详解
Aug 14 Python
新年福利来一波之Python轻松集齐五福(demo)
Jan 20 Python
Tensorflow 卷积的梯度反向传播过程
Feb 10 Python
python实现超级马里奥
Mar 18 Python
python 弧度与角度互转实例
Apr 15 Python
python 中的命名空间,你真的了解吗?
Aug 19 Python
基于Python实现天天酷跑功能
Jan 06 Python
pytorch 两个GPU同时训练的解决方案
Jun 01 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
ThinkPHP中RBAC类的四种用法分析
2014/11/24 PHP
非集成环境的php运行环境(Apache配置、Mysql)搭建安装图文教程
2016/04/12 PHP
PHP PDOStatement::fetchAll讲解
2019/01/31 PHP
PHP实现随机发扑克牌
2020/04/22 PHP
jQuery 隔行换色 支持键盘上下键,按Enter选定值
2009/08/02 Javascript
下载站控制介绍字数显示的脚本 显示全部 隐藏介绍等功能
2009/09/19 Javascript
div模拟选择框示例代码
2013/11/03 Javascript
jquery 中的each()跳出循环的语句
2014/05/23 Javascript
jQuery使用before()和after()在元素前后添加内容的方法
2015/03/26 Javascript
js查看一个函数的执行时间实例代码
2015/09/12 Javascript
JS实现图片延迟加载并淡入淡出效果的简单方法
2016/08/25 Javascript
Bootstrap优化站点资源、响应式图片、传送带使用详解3
2016/10/14 Javascript
AngularJS递归指令实现Tree View效果示例
2016/11/07 Javascript
原生node.js案例--前后台交互
2017/02/20 Javascript
JavaScript 过滤关键字
2017/03/20 Javascript
vue2.0实战之基础入门(1)
2017/03/27 Javascript
详解node如何让一个端口同时支持https与http
2017/07/04 Javascript
HTML5+JS+JQuery+ECharts实现异步加载问题
2017/12/16 jQuery
vue 引入公共css文件的简单方法(推荐)
2018/01/20 Javascript
vue swipe自定义组件实现轮播效果
2019/07/03 Javascript
Vue.js使用axios动态获取response里的data数据操作
2020/09/08 Javascript
pymssql ntext字段调用问题解决方法
2008/12/17 Python
如何搜索查找并解决Django相关的问题
2014/06/30 Python
Python中index()和seek()的用法(详解)
2017/04/27 Python
python+matplotlib绘制简单的海豚(顶点和节点的操作)
2018/01/02 Python
Python实现爬虫设置代理IP和伪装成浏览器的方法分享
2018/05/07 Python
django 实现电子支付功能的示例代码
2018/07/25 Python
python协程之动态添加任务的方法
2019/02/19 Python
在VS2017中用C#调用python脚本的实现
2019/07/31 Python
解决python Jupyter不能导入外部包问题
2020/04/15 Python
在python中使用nohup命令说明
2020/04/16 Python
html5使用Canvas绘图的使用方法
2017/11/21 HTML / CSS
见义勇为事迹材料
2014/12/24 职场文书
在校生证明
2015/06/17 职场文书
Spring Security动态权限的实现方法详解
2022/06/16 Java/Android
MutationObserver在页面水印实现起到的作用详解
2022/07/07 Javascript