阿牛 发表于 2017-4-21 07:03:04

Python functools

首先看下functools包含的方法

Python 2.7.2 (default, Jun 20 2012, 16:23:33)
on darwin
Type "help", "copyright", "credits" or "license" for more information.
>>> import functools
>>> dir(functools)
['WRAPPER_ASSIGNMENTS', 'WRAPPER_UPDATES', '__builtins__', '__doc__', '__file__', '__name__', '__package__', 'cmp_to_key', 'partial', 'reduce', 'total_ordering', 'update_wrapper', 'wraps']

一、partial函数
他可以重新绑定函数的可选参数,生成一个callable的partial对象
对于已知的函数参数若可以提前获知,可以减少更多的参数调用。
In : from functools import partial
In : int2 = partial(int, base=2)
In : int2('10')
Out: 2


二、wraps
wraps主要是用来包装函数,使被包装含数更像原函数,它是对partial(update_wrapper, ...)的简单包装,partial主要是用来修改函数签名,使一些参数固化,以提供一个更简单的函数供以后调用
update_wrapper是wraps的主要功能提供者,它负责考贝原函数的属性,默认是:'__module__', '__name__', '__doc__', '__dict__'。

>>> 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'

三、reduce
function的reduce与python内置的reduce是一样的
reduce()函数:reduce(func,seq[,init]),用二元函数func对序列seq中的元素进行处理,每次处理两个数据项(一个是前次处理的结果,一个是序列中的下一个元素),如此反复的递归处理,最后对整个序列求出一个单一的返回值。

>>> l=
>>> reduce((lambda x,y:x+y),l)
21
>>> import functools
>>> functools.reduce((lambda x,y:x+y),l)
21

参考资料:
http://docs.python.org/2/library/functools.html
http://www.cnblogs.com/huxi/archive/2011/03/01/1967600.html
http://blog.csdn.net/baizhiwen_2005/article/details/1181770
页: [1]
查看完整版本: Python functools