使用装饰器时带括号与不带括号的区别
生活随笔
收集整理的這篇文章主要介紹了
使用装饰器时带括号与不带括号的区别
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
之前我們在一個用于統計函數調用消耗時間的裝飾器中寫了一個裝飾器,用于統計函數調用時間。代碼如下:
from time import time from time import sleepdef count_time():def tmp(func):def wrapped(*args, **kargs):begin_time = time()result = func(*args, **kargs)end_time = time()cost_time = end_time - begin_timeprint '%s called cost time : %s' %(func.__name__, cost_time)return resultreturn wrappedreturn tmp對于該裝飾器,我們必須這樣使用:
@count_time() def test():sleep(0.5)if __name__ == '__main__':test()這里注意,裝飾器后面加了括號。
如果我們不加括號:
@count_time def test():sleep(0.5)if __name__ == '__main__':test()就會產生錯誤:
Traceback (most recent call last):File "16.py", line 16, in <module>@count_time TypeError: count_time() takes no arguments (1 given)?
但是很多裝飾器使用時,是不必加括號的,那么這是怎么回事?
?
我們將上面的裝飾器進行改寫:
from time import time from time import sleep import sysdef count_time(func):def wrapped(*args, **kargs):begin_time = time()result = func(*args, **kargs)end_time = time()cost_time = end_time - begin_timeprint '%s called cost time : %s ms' %(func.__name__, float(cost_time)*1000)return resultreturn wrapped此時,就不需要加括號了。
這二者的區別在于,第一個存在括號,允許用戶傳入自定義信息,所以需要額外包裝一層,不加括號的版本則不需要。
?
所以當我們需要自定義裝飾器內的某些message時,就需要采用加括號的方式。
對于這個統計時間的裝飾器,我們可以這樣自定義信息:
#coding: utf-8 from time import time from time import sleepdef count_time(msg):def tmp(func):def wrapped(*args, **kargs):begin_time = time()result = func(*args, **kargs)end_time = time()cost_time = end_time - begin_timeprint 'msg: %s ,%s called cost time : %s' %(msg, func.__name__, cost_time)return resultreturn wrappedreturn tmp然后這樣使用:
@count_time("foobar") def test():sleep(0.5)@count_time("測試消息") def test2():sleep(0.7)if __name__ == '__main__':test()test2()結果如下:
msg: foobar ,test called cost time : 0.501540899277 msg: 測試消息 ,test2 called cost time : 0.701622009277?
后面綜合前面幾篇,寫一個完整的裝飾器教程。
轉載于:https://www.cnblogs.com/inevermore/p/4219882.html
總結
以上是生活随笔為你收集整理的使用装饰器时带括号与不带括号的区别的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: Linq之隐式类型、自动属性、初始化器、
- 下一篇: easyui datagrid loca