`

Python functools

 
阅读更多

原文地址:
http://2057.iteye.com/blog/1798472


首先看下functools包含的方法

Python代码  收藏代码
Python 2.7.2 (default, Jun 20 2012, 16:23:33) 
 
[GCC 4.2.1 Compatible Apple Clang 4.0 (tags/Apple/clang-418.0.60)] 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对象

对于已知的函数参数若可以提前获知,可以减少更多的参数调用。 (就是减少输入参数)

Python代码  收藏代码
In [16]: from functools import partial 
In [17]: int2 = partial(int, base=2) 
In [18]: int2('10') 
Out[18]: 2 

实例:

from operator import add

import functools

print add(1,2)

"""

输出:

3

"""

add1 = functools.partial(add,1)

print add1(10)

"""

输出:

11

"""


二、wraps

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

Python代码  收藏代码
>>> 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中的元素进行处理,每次处理两个数据项(一个是前次处理的结果,一个是序列中的下一个元素),如此反复的递归处理,最后对整个序列求出一个单一的返回值。

Python代码  收藏代码
>>> l=[1,2,3,4,5,6] 
 
>>> 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

 

分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics