python functools模块
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 functools模块的更多相关文章
- Python标准模块--functools
1 模块简介 functools,用于高阶函数:指那些作用于函数或者返回其它函数的函数,通常只要是可以被当做函数调用的对象就是这个模块的目标. 在Python 2.7 中具备如下方法, cmp_to_ ...
- python 装饰器和 functools 模块
转自:http://blog.jkey.lu/2013/03/15/python-decorator-and-functools-module/ 什么是装饰器? 在 python 语言里第一次看到装饰 ...
- python中 functools模块 闭包的两个好朋友partial偏函数和wraps包裹
前一段时间学习了python当中的装饰器,主要利用了闭包的原理.后来呢,又见到了python当中的functools模块,里面有很多实用的功能.今天我想分享一下跟装饰器息息相关的两个函数partial ...
- python中的functools模块
functools模块可以作用于所有的可以被调用的对象,包括函数 定义了__call__方法的类等 1 functools.cmp_to_key(func) 将比较函数(接受两个参数,通过比较两个参数 ...
- Python标准库笔记(9) — functools模块
functools 作用于函数的函数 functools 模块提供用于调整或扩展函数和其他可调用对象的工具,而无需完全重写它们. 装饰器 partial 类是 functools 模块提供的主要工具, ...
- Python面向切面编程-语法层面和functools模块
1,Python语法层面对面向切面编程的支持(方法名装饰后改变为log) __author__ = 'Administrator' import time def log(func): def wra ...
- Python中functools模块函数解析
Python自带的 functools 模块提供了一些常用的高阶函数,也就是用于处理其它函数的特殊函数.换言之,就是能使用该模块对可调用对象进行处理. functools模块函数概览 functool ...
- Python使用functools模块中的partial函数生成偏函数
所谓偏函数即是规定了固定参数的函数,在函数式编程中我们经常可以用到,这里我们就来看一下Python使用functools模块中的partial函数生成偏函数的方法 python 中提供一种用于对函数固 ...
- python的collections模块和functools模块
collections是Python内建的一个集合模块,提供了许多有用的集合类. namedtuple 我们知道tuple可以表示不变集合,例如,一个点的二维坐标就可以表示成: >>> ...
随机推荐
- ubuntu 14.04 编译安装 nginx
下载源码包 nginx 地址:http://nginx.org/en/download.html 下载nginx 1.4.7 编译前先安装两个包: 直接编译安装会碰到缺少pcre等问题,这时候只要到 ...
- JDK自带方法实现消息摘要运算
啊,有点小注释,懒得介绍了,就贴个代码吧,大意理解就可以了. package jdbc.pro.lin; import java.security.InvalidKeyException; impor ...
- android Activity 生命周期
今天第一次详细学习android,主要了解了一下activity的生命周期,下面详细说一下自己的简介: 在Actity中最主要的有一下几个方法: protectedvoid onCreate(Bund ...
- 关于wordpress忘记密码 找回密码的方式
1.通过直接修改数据库中密码的加密字符(如果wordpress的版本不同,那么此方法是不好实现的) 2.使用找回密码的方式:通过邮箱找回密码 前端登录密码错误后 会显示 错误); 方法二 打开WP ...
- oracle 非空闲等待事件排查
想必大家都知道Oracle的等待时间分为两种,一种我们称之为“空闲等待事件”,另外一种称之为“非空闲等待事件”.“空闲等待事件”——作为DBA可以不用过分的关注这类等待事件.“非空闲等待事件”——当D ...
- JS异步阻塞的迷思
还是百度前端技术学院的“任务十九”可视化排序算法的题,在写出快速排序算法之后,要求用动画的形式把这个排序过程呈现出来.排序过程在CPU里不过是瞬间的事,但要转换成“缓慢的”动画效果给人类看,就不得不把 ...
- Linux下追踪函数调用,打印栈帧
事情的起因是这样的,之前同事的代码有一个内存池出现了没有回收的情况.也就是是Pop出来的对象没有Push回去,情况很难复现,所以在Pop里的打印日志,跟踪是谁调用了它,我想在GDB调试里可以追踪调用的 ...
- QTableView使用自定义委托(QItemDelegate)
需要在表格中绘制流程图,主要有箭头,方向,颜色,字符串,由于QTableView没有可用的绘制函数,所以需要自己去定义. 委托(delegate)继承QItemDelegate,模型(model)继承 ...
- ueditor富文本编辑在 asp.net MVC下使用步骤
mvc项目中用到了这个富文本编辑就试着把遇到的问题个使用步骤在这里记录一下,希望大家少走弯路. 1.首先我们先下载net版本的uediot r.
- oracle sqlldr控制文件模板
Sqlldr userid=lgone/tiger control=a.ctl LOAD DATA INFILE 't.dat' // 要导入的文件 // INFILE 'tt.date' // 导入 ...