2007-11-01
python小例子之8 -- decorator的使用
关键字: decorator 函数式编程主题: decorator的使用
环境: winxp pro + sp2 + python2.5
备注: 请注意,凡是在源代码文件中使用了中文字符,请最好保存为utf-8格式
备注: 请注意,凡是在源代码文件中使用了中文字符,请最好保存为utf-8格式
本文与另外一篇blog文章内容相关:python中如何简单的实现decorator模式--由django admin源码所得体会
本文就是因kdekid 在该blog回帖后,我对python decorator的使用整理出的一点心得,在上述提及的blog中的代码亦可修改为本文所描述的方式,各位同学可自己试试 :)
具体的语法描述可参考: python manuals -- Language Reference -- 7.Compound statements -- 7.6 Function definitions 

代码:
python 代码
- # decorator_arg.py
- # 修饰函数
- def decorator(fun):
- def ifun(*args, **kwargs):
- args = (i+1 for i in args)
- return fun(*args, **kwargs)
- return ifun
- def decorator1(arg):
- def _decorator1(fun):
- def ifun(*args, **kwargs):
- args = (i+arg for i in args)
- return fun(*args, **kwargs)
- return ifun
- return _decorator1
- # 被修饰函数1
- @decorator
- def fun1(x,y,z):
- return x+y+z
- arg = 2
- # 被修饰函数2
- @decorator1(arg)
- def fun2(x,y,z):
- return x+y+z
- # 测试代码
- a = 3
- b = 4
- c = 5
- print fun1(a,b,c)
- print fun2(a,b,c)
测试:保存为文件,直接执行即可
测试结果:
控制台输出:
- >>>
- 15
- 18
发表评论
提醒: 该博客已发表在公共论坛,博客所有留言会成为论坛回贴,留言请注意遵守论坛发贴规则
- 浏览: 89787 次
- 性别:

- 来自: 成都

- 详细资料
搜索本博客
链接
最新评论
-
谈谈django中图片上传的2 ...
又试了一下,pic = StringIO.StringIO() im.sa ...
-- by ahuaxuan -
谈谈django中图片上传的2 ...
周末在家里试了一下,pic = StringIO.StringIO() i ...
-- by ahuaxuan -
linux下我使用的软件工具 ...
LS EVA够用了。
-- by 卡拉阿风 -
linux下我使用的软件工具 ...
自从用了ubuntu 就不中毒了 唯一的痛就是qq 虽然现在qq有了linux版 ...
-- by baseworld -
linux下我使用的软件工具 ...
supermy 写道linux现在的驱动识别已经很强了。 装那么多工具干吗。花两 ...
-- by 渐行渐远






评论排行榜