Python的functools模块
来源:互联网 发布:珠海网络布线 编辑:程序博客网 时间:2024/05/20 12:47
这个模块提供了3个有趣的函数,这里介绍下其用法。
首先是partial函数,它可以重新绑定函数的可选参数,生成一个callable的partial对象:
接着是update_wrapper函数,它可以把被封装函数的__name__、__module__、__doc__和 __dict__都复制到封装函数去:
最后是wraps函数,它将update_wrapper也封装了进来:
首先是partial函数,它可以重新绑定函数的可选参数,生成一个callable的partial对象:
>>> int('10') # 实际上等同于int('10', base=10)和int('10', 10)10>>> int('10', 2) # 实际上是int('10', base=2)的缩写2>>> from functools import partial>>> int2 = partial(int, 2) # 这里我没写base,结果就出错了>>> int2('10')Traceback (most recent call last): File "<stdin>", line 1, in <module>TypeError: an integer is required>>> int2 = partial(int, base=2) # 把base参数绑定在int2这个函数里>>> int2('10') # 现在缺省参数base被设为2了2>>> int2('10', 3) # 没加base,结果又出错了Traceback (most recent call last): File "<stdin>", line 1, in <module>TypeError: keyword parameter 'base' was given by position and by name>>> int2('10', base=3)3>>> type(int2)<type 'functools.partial'>
从中可以看出,唯一要注意的是可选参数必须写出参数名。接着是update_wrapper函数,它可以把被封装函数的__name__、__module__、__doc__和 __dict__都复制到封装函数去:
#-*- coding: gbk -*-def thisIsliving(fun): def living(*args, **kw): return fun(*args, **kw) + '活着就是吃嘛。' return living@thisIslivingdef whatIsLiving(): "什么是活着" return '对啊,怎样才算活着呢?'print whatIsLiving()print whatIsLiving.__doc__printfrom functools import update_wrapperdef thisIsliving(fun): def living(*args, **kw): return fun(*args, **kw) + '活着就是吃嘛。' return update_wrapper(living, fun)@thisIslivingdef whatIsLiving(): "什么是活着" return '对啊,怎样才算活着呢?'print whatIsLiving()print whatIsLiving.__doc__
结果:对啊,怎样才算活着呢?活着就是吃嘛。不过也没多大用处,毕竟只是少写了4行赋值语句而已。
None
对啊,怎样才算活着呢?活着就是吃嘛。
什么是活着
最后是wraps函数,它将update_wrapper也封装了进来:
#-*- coding: gbk -*-from functools import wrapsdef thisIsliving(fun): @wraps(fun) def living(*args, **kw): return fun(*args, **kw) + '活着就是吃嘛。' return living@thisIslivingdef whatIsLiving(): "什么是活着" return '对啊,怎样才算活着呢?'print whatIsLiving()print whatIsLiving.__doc__
结果还是一样的:对啊,怎样才算活着呢?活着就是吃嘛。
什么是活着
0 0
- Python的functools模块
- Python的functools模块
- Python的functools模块
- Python的functools模块
- Python的functools模块
- Python的functools模块
- python的functools进阶模块
- Python的functools模块详解
- python模块 - functools模块
- python的functools模块常用方法介绍
- Python模块(functools)
- python functools模块
- PYTHON-FUNCTOOLS模块
- Python functools模块学习总结
- python--functools的使用
- Python装饰器及functools模块
- python 装饰器和 functools 模块
- functools模块
- Scala编程指南:面向对象编程
- 二分查找算法
- 如何使带背景图片的Button按钮中的文字居中偏上显示
- STL学习之slist
- div和span用法的区别
- Python的functools模块
- 关于SQL Server将一列的多行内容拼接成一行的问题讨论 [转]
- Python内置类型转换函数
- asp简单学习笔记
- Java利用poi读写Excel需要注意的问题
- c++中数组名与函数的区别
- android开发中的java.lang.StackOverflowError错误
- 网络流行语“不作不死”英文入选美国词典
- Java中的Timer和TimerTask的使用