本文总结分析了Python装饰器简单用法。分享给大家供大家参考,具体如下:
装饰器在python中扮演着很重要的作用,例如插入日志等,装饰器可以为添加额外的功能同时又不影响业务函数的功能。
比如,运行业务函数fun()同时打印运行花费的时间
1. 运行业务函数fun()同时打印运行花费的时间
import timedef dec(fun): start = time.time() fun() end = time.time() a = end - start print adef myfun(): print 'run myfunction'dec(myfun)运行结果
(virt2) root@ubuntu:/home/z# python z.py
run myfunction
0.00108599662781
但是每次运行myfun都要调用dec,下面作下变动解决这个问题
2.
import timedef dec(fun): def wrap(): start = time.time() fun() end = time.time() a = end - start print a return wrapdef myfun(): print 'run myfunction'myfun=dec(myfun)myfun()运行结果:
(virt2) root@ubuntu:/home/z# python z.py
run myfunction
0.00122618675232
这个装饰器dec就实现了,并且不影响函数myfun功能
3. 装饰器@符
import timedef dec(fun): def wrap(): start = time.time() fun() end = time.time() a = end - start print a return wrap@decdef myfun(): print 'run myfunction'myfun()结果
(virt2) root@ubuntu:/home/z# python z.py
run myfunction
0.000470876693726
使用了@后,就不用给myfun重新赋值了
@dec就相当于myfun=dec(myfun)
例子:
def level(leveel): def debug(func): def wrapper(*args, **kwargs): print("[DEBUG]: enter {}()".format(func.__name__),leveel) return func(*args, **kwargs) return wrapper return debug@level(leveel='debuging')def say(something): print ("hello {}!".format(something))say(123)输出:
('[DEBUG]: enter say()', 'debuging')
hello 123!
输出:
[INFO]: enter function say()
say 123!
更多关于Python相关内容可查看本站专题:《Python数据结构与算法教程》、《Python Socket编程技巧总结》、《Python函数使用技巧总结》、《Python字符串操作技巧汇总》及《Python入门与进阶经典教程》
希望本文所述对大家Python程序设计有所帮助。