Python的functools模块
来源:互联网 发布:大数据阅读答案 编辑:程序博客网 时间:2024/05/20 15:12
首先是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__
结果还是一样的:对啊,怎样才算活着呢?活着就是吃嘛。什么是活着
先贴过来,后续再学习。
原文地址:http://www.keakon.net/2009/04/12/Python%E7%9A%84functools%E6%A8%A1%E5%9D%97
- 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模块
- C语言零星笔记--(const、typedef)
- POJ 2503 Babelfish
- HTTP 返回状态值详解
- URL编码和解码
- Android回调机制
- Python的functools模块
- UITableViewCell的选中时的颜色及tableViewCell的selecte与deselecte
- 基本数据结构之线性表-链表
- HashSet的使用
- POJ_2142_The Balance(模线性方程)
- 出差准备攻略(个人备忘录)!
- POJ 2033 alpha code 的译码数目
- 调用Oracle EBS Webservice常见的几个错误
- 守护线程总结