Python的functools模块

来源:互联网 发布:java视频播放器全屏 编辑:程序博客网 时间:2024/05/20 12:22
这个模块提供了3个有趣的函数,这里介绍下其用法。

首先是partial函数,它可以重新绑定函数的可选参数,生成一个callable的partial对象:

[python] view plain copy
 print?
  1. >>> int('10'# 实际上等同于int('10', base=10)和int('10', 10)  
  2. 10  
  3. >>> int('10'2# 实际上是int('10', base=2)的缩写  
  4. 2  
  5. >>> from functools import partial  
  6. >>> int2 = partial(int, 2# 这里我没写base,结果就出错了  
  7. >>> int2('10')  
  8. Traceback (most recent call last):  
  9.   File "<stdin>", line 1in <module>  
  10. TypeError: an integer is required  
  11. >>> int2 = partial(int, base=2# 把base参数绑定在int2这个函数里  
  12. >>> int2('10'# 现在缺省参数base被设为2了  
  13. 2  
  14. >>> int2('10'3# 没加base,结果又出错了  
  15. Traceback (most recent call last):  
  16.   File "<stdin>", line 1in <module>  
  17. TypeError: keyword parameter 'base' was given by position and by name  
  18. >>> int2('10', base=3)  
  19. 3  
  20. >>> type(int2)  
  21. <type 'functools.partial'>  

从中可以看出,唯一要注意的是可选参数必须写出参数名。

接着是update_wrapper函数,它可以把被封装函数的__name__、__module__、__doc__和 __dict__都复制到封装函数去:


[python] view plain copy
 print?
  1. #-*- coding: gbk -*-  
  2.   
  3. def thisIsliving(fun):  
  4.   def living(*args, **kw):  
  5.     return fun(*args, **kw) + '活着就是吃嘛。'  
  6.   return living  
  7.  
  8. @thisIsliving  
  9. def whatIsLiving():  
  10.   "什么是活着"  
  11.   return '对啊,怎样才算活着呢?'  
  12.   
  13. print whatIsLiving()  
  14. print whatIsLiving.__doc__  
  15.   
  16. print  
  17.   
  18. from functools import update_wrapper  
  19. def thisIsliving(fun):  
  20.   def living(*args, **kw):  
  21.     return fun(*args, **kw) + '活着就是吃嘛。'  
  22.   return update_wrapper(living, fun)  
  23.  
  24. @thisIsliving  
  25. def whatIsLiving():  
  26.   "什么是活着"  
  27.   return '对啊,怎样才算活着呢?'  
  28.   
  29. print whatIsLiving()  
  30. print whatIsLiving.__doc__  

结果:

对啊,怎样才算活着呢?活着就是吃嘛。
None

对啊,怎样才算活着呢?活着就是吃嘛。
什么是活着
不过也没多大用处,毕竟只是少写了4行赋值语句而已。

最后是wraps函数,它将update_wrapper也封装了进来:

[python] view plain copy
 print?
  1. #-*- coding: gbk -*-  
  2.   
  3. from functools import wraps  
  4.   
  5. def thisIsliving(fun):  
  6.   @wraps(fun)  
  7.   def living(*args, **kw):  
  8.     return fun(*args, **kw) + '活着就是吃嘛。'  
  9.   return living  
  10.  
  11. @thisIsliving  
  12. def whatIsLiving():  
  13.   "什么是活着"  
  14.   return '对啊,怎样才算活着呢?'  
  15.   
  16. print whatIsLiving()  
  17. print whatIsLiving.__doc__  

结果还是一样的:

对啊,怎样才算活着呢?活着就是吃嘛。
什么是活着
0 0
原创粉丝点击