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,这里就不谈论这个方法了。