Python装饰器用法示例小结
本文实例讲述了Python装饰器用法。分享给大家供大家参考,具体如下:
下面的程序示例了python装饰器的使用:
示例一:
defouter(fun):
printfun
defwrapper(arg):
result=fun(arg)
print'over!'
returnresult
returnwrapper
@outer
deffunc1(arg):
print'func1',arg
return'verygood!'
response=func1('python')
printresponse
printfunc1
运行结果:
func1python over! verygood!
示例二:
#!/usr/bin/envpython
#coding:utf-8
defFilter(before_func,after_func):
printbefore_func
printafter_func
defouter(main_func):
printmain_func
defwrapper(request,kargs):
before_result=before_func(request,kargs)
if(before_result!=None):
returnbefore_result;
main_result=main_func(request,kargs)
if(main_result!=None):
returnmain_result;
after_result=after_func(request,kargs)
if(after_result!=None):
returnafter_result;
returnwrapper
returnouter
defbefore(request,kargs):
printrequest,kargs,'之前!'
defafter(request,kargs):
printrequest,kargs,'之后!'
@Filter(before,after)
defmain(request,kargs):
printrequest,kargs
main('hello','python')
printmain
运行结果:
hellopython之前! hellopython hellopython之后!
我们可以加上很多断点,在Debug模式下运行,查看程序一步一步的运行轨迹。。。
更多关于Python相关内容可查看本站专题:《Python数据结构与算法教程》、《PythonSocket编程技巧总结》、《Python函数使用技巧总结》、《Python字符串操作技巧汇总》及《Python入门与进阶经典教程》
希望本文所述对大家Python程序设计有所帮助。