Python装饰器用法实例分析
本文实例讲述了Python装饰器用法。分享给大家供大家参考,具体如下:
无参数的装饰器
#coding=utf-8 deflog(func): defwrapper(): print'beforecalling',func.__name__ func() print'endcalling',func.__name__ returnwrapper @log defhello(): print'hello' @log defhello2(name): print'hello',name if__name__=='__main__': hello()
运行结果:
beforecalling hello
hello
endcalling hello
带参数的装饰器:
#coding=utf-8 deflog(func): defwrapper(name): print'beforecalling',func.__name__ func(name) print'endcalling',func.__name__ returnwrapper @log defhello(name): print'hello',name @log defhello2(name): print'hello',name if__name__=='__main__': hello('haha')
运行结果:
beforecalling hello
hellohaha
endcalling hello
多个参数的时候:
#coding=utf-8 deflog(func): ''' *无名字的参数 **有名字的参数 :paramfunc: :return: ''' defwrapper(*args,**kvargs): print'beforecalling',func.__name__ print'args',args,'kvargs',kvargs func(*args,**kvargs) print'endcalling',func.__name__ returnwrapper @log defhello(name,age): print'hello',name,age @log defhello2(name): print'hello',name if__name__=='__main__': hello('haha',2) hello(name='hehe',age=3)
输出:
endcalling hello
beforecalling hello
args()kvargs{'age':3,'name':'hehe'}
hellohehe3
endcalling hello
装饰器里带参数的情况
本质就是嵌套函数
#coding=utf-8 deflog(level,*args,**kvargs): definner(func): defwrapper(*args,**kvargs): printlevel,'beforecalling',func.__name__ printlevel,'args',args,'kvargs',kvargs func(*args,**kvargs) printlevel,'endcalling',func.__name__ returnwrapper returninner @log(level='INFO') defhello(name,age): print'hello',name,age @log defhello2(name): print'hello',name if__name__=='__main__': hello('haha',2)
运行输出:
INFObeforecalling hello
INFOargs('haha',2)kvargs{}
hellohaha2
INFOendcalling hello
更多关于Python相关内容可查看本站专题:《Python数据结构与算法教程》、《PythonSocket编程技巧总结》、《Python函数使用技巧总结》、《Python字符串操作技巧汇总》及《Python入门与进阶经典教程》
希望本文所述对大家Python程序设计有所帮助。