python functools

functools 是python2.5被引人的,文档在http://docs.python.org/library/functools.html

functools里有partial,reduce,update_wrapper,wraps

我们一个一个的来理解

1. functools.reduce和python内置的reduce是一样的,

2. functools.partial

一个带 n 个参数,partial 的函数固化第一个参数为固定参数,并返回另一个带 n-1 个参数函数对象.

from operator import add
import functools
print add(1,2) #3
add1 = functools.partial(add,1)
print add1(10) #11

3. update_wrapper

文档中是这样描述的

The main intended use for this function is in decorator functions which wrap the decorated function and return the wrapper. If the wrapper function is not updated, the metadata of the returned function will reflect the wrapper definition rather than the original function definition, which is typically less than helpful.

复制代码
from functools import wraps
from functools import update_wrapper
def decorator0(f):
def wrapper(*args, **kwds):
print 'Calling decorated function---------------------0'
return f(*args, **kwds)
return wrapper

def decorator1(f):
def wrapper(*args, **kwds):
print 'Calling decorated function---------------------1'
return f(*args, **kwds)
return wrapper

@decorator0
def example():
"""Docstring"""
print 'Called example function'
example()

print '--------------------------------'

update_wrapper(example,decorator1)
example()
复制代码

4. functools.wraps,文档描叙

This is a convenience function for invoking partial(update_wrapper, wrapped=wrapped,assigned=assigned, updated=updated) as a function decorator when defining a wrapper function.

其实也就是相当于在调用了partial,使用wraps可以把整个function的属性都带上。

复制代码
>>> from functools import wraps
>>> def my_decorator(f):
... @wraps(f)
...
def wrapper(*args, **kwds):
...
print 'Calling decorated function'
...
return f(*args, **kwds)
...
return wrapper
...
>>> @my_decorator
...
def example():
...
"""Docstring"""
...
print 'Called example function'
...
>>> example()
Calling decorated function
Called example function
>>> example.__name__
'example'
>>> example.__doc__
'Docstring'
复制代码

另外python2.7里添加了cmp_to_key,total_ordering,我用的是2.6,这里就不谈论这个方法了。


http://www.cnblogs.com/twelfthing/articles/2145656.html

  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值