本文實例講述了Python裝飾器用法。分享給大家供大家參考,具體如下:
下面的程序示例了python裝飾器的使用:
示例一:
def outer(fun): print fun def wrapper(arg): result=fun(arg) print 'over!' return result return wrapper@outerdef func1(arg): print 'func1',arg return 'very good!'response=func1('python')print responseprint func1運行結果:
<function func1 at 0x02A67D70>func1 pythonover!very good!<function wrapper at 0x02A67CF0>
示例二:
#!/usr/bin/env python#coding:utf-8def Filter(before_func,after_func): print before_func print after_func def outer(main_func): print main_func def wrapper(request,kargs): before_result=before_func(request,kargs) if(before_result!=None): return before_result; main_result=main_func(request,kargs) if(main_result!=None): return main_result; after_result=after_func(request,kargs) if(after_result!=None): return after_result; return wrapper return outerdef before(request,kargs): print request,kargs,'之前!'def after(request,kargs): print request,kargs,'之后!'@Filter(before,after)def main(request,kargs): print request,kargsmain('hello','python')print main運行結果:
<function before at 0x02AC7BF0><function after at 0x02AC7C30><function main at 0x02AC7CF0>hello python 之前!hello pythonhello python 之后!<function wrapper at 0x02AC7D30>
我們可以加上很多斷點,在Debug模式下運行,查看程序一步一步的運行軌跡。。。
更多關于Python相關內容可查看本站專題:《Python數據結構與算法教程》、《Python Socket編程技巧總結》、《Python函數使用技巧總結》、《Python字符串操作技巧匯總》及《Python入門與進階經典教程》
希望本文所述對大家Python程序設計有所幫助。
新聞熱點
疑難解答