python小例子之8 -- decorator的使用
主题: decorator的使用环境: winxp pro + sp2 + python2.5
备注: 请注意,凡是在源代码文件中使用了中文字符,请最好保存为utf-8格式
本文与另外一篇blog文章内容相关:python中如何简单的实现decorator模式--由django admin源码所得体会
本文就是因kdekid 在该blog回帖后,我对python decorator的使用整理出的一点心得,在上述提及的blog中的代码亦可修改为本文所描述的方式,各位同学可自己试试 :)
具体的语法描述可参考: python manuals -- Language Reference -- 7.Compound statements -- 7.6 Function definitions http://bluecrystal.iteye.com/javascripts/fckeditor/editor/images/smiley/msn/lightbulb.gif
代码:
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
页:
[1]