【转】functools模块

上一篇 / 下一篇  2016-06-30 19:20:35 / 个人分类:python

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 个参数函数对象.

fromoperatorimportadd
importfunctools
printadd(1,2)#3
add1=functools.partial(add,1)
printadd1(10)#11

3. update_wrapper

文档中是这样描述的

The main intended use for this function is indecoratorfunctions 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.

复制代码
fromfunctoolsimportwraps
fromfunctoolsimportupdate_wrapper
defdecorator0(f):
defwrapper(*args,**kwds):
print'Calling decorated function---------------------0'
returnf(*args,**kwds)
returnwrapper

defdecorator1(f):
defwrapper(*args,**kwds):
print'Calling decorated function---------------------1'
returnf(*args,**kwds)
returnwrapper

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

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

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

4. functools.wraps,文档描叙

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

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

复制代码
>>>fromfunctoolsimportwraps
>>>defmy_decorator(f):
... @wraps(f)
...
defwrapper(*args,**kwds):
...
print'Calling decorated function'
...
returnf(*args,**kwds)
...
returnwrapper
...
>>>@my_decorator
...
defexample():
...
"""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,这里就不谈论这个方法了。


TAG:

 

评分:0

我来说两句

我的栏目

日历

« 2022-01-18  
      1
2345678
9101112131415
16171819202122
23242526272829
3031     

数据统计

  • 访问量: 2407
  • 日志数: 10
  • 文件数: 2
  • 建立时间: 2010-02-21
  • 更新时间: 2016-06-30

RSS订阅

Open Toolbar