上一篇文章: Python是動態語言:動態添加或刪除屬性、方法
下一篇文章: 私有化規則與屬性Property
裝飾器功能:python
- 引入日誌
- 函數執行時間統計
- 執行函數前預備處理
- 執行函數後清理功能
- 權限校驗
- 緩存
實例:segmentfault
from time import ctime,sleep def time_fun(func): #內部包裹函數 def wrapped_fun(): #ctime():打印當前時間 print("%s 在 %s 時被調用"%(func.__name__,ctime())) #執行函數執行 func() #把內部嵌套函數做爲對象返回 return wrapped_fun @time_fun def test(): print("test 執行了") test() #休眠3秒 sleep(3) test()
結果:緩存
test 在 Wed Aug 15 22:19:51 2018 時被調用 test 執行了 test 在 Wed Aug 15 22:19:53 2018 時被調用 test 執行了
實例:app
from time import ctime,sleep def time_fun(func): #內部包裹函數 def wrapped_fun(a,b): #ctime():打印當前時間 print("%s 在 %s 時被調用"%(func.__name__,ctime())) #執行函數執行 func(a,b) #把內部嵌套函數做爲對象返回 return wrapped_fun @time_fun def test(a,b): print(a+b) test(1,2) #休眠3秒 sleep(3) test(3,4)
結果:函數
test 在 Wed Aug 15 22:23:07 2018 時被調用 3 test 在 Wed Aug 15 22:23:10 2018 時被調用 7
實例:日誌
from time import ctime,sleep def time_fun(func): #內部包裹函數 def wrapped_fun(*args,**kwargs): #ctime():打印當前時間 print("%s 在 %s 時被調用"%(func.__name__,ctime())) #執行函數執行 func(*args,**kwargs) #把內部嵌套函數做爲對象返回 return wrapped_fun @time_fun def test(a,b,c): print(a+b+c) test(1,2,3) #休眠3秒 sleep(3) test(3,4,5)
結果:code
test 在 Wed Aug 15 22:26:36 2018 時被調用 6 test 在 Wed Aug 15 22:26:39 2018 時被調用 12
實例:對象
from time import ctime,sleep def time_fun(func): #內部包裹函數 def wrapped_fun(*args,**kwargs): #ctime():打印當前時間 print("%s 在 %s 時被調用"%(func.__name__,ctime())) #執行函數執行 return func(*args,**kwargs) #把內部嵌套函數做爲對象返回 return wrapped_fun @time_fun def test(a,b,c): print("test--",a+b+c) @time_fun def test2(a,b,c): return a+b+c test(1,2,3) print(test2(1,2,3)) #休眠3秒 sleep(3) test(1,2,3) print(test2(3,4,5))
結果:get
test 在 Wed Aug 15 22:31:14 2018 時被調用 test-- 6 test2 在 Wed Aug 15 22:31:14 2018 時被調用 6 test 在 Wed Aug 15 22:31:17 2018 時被調用 test-- 6 test2 在 Wed Aug 15 22:31:17 2018 時被調用 12
實例:it
from time import ctime,sleep def time_fun_pre(pre="hello"): def time_fun(func): # 內部包裹函數 def wrapped_fun(*args, **kwargs): # ctime():打印當前時間 print("%s 在 %s 時被調用,pre參數爲:%s" % (func.__name__, ctime(),pre)) # 執行函數執行 return func(*args, **kwargs) # 把內部嵌套函數做爲對象返回 return wrapped_fun return time_fun @time_fun_pre("mark_test") def test(a,b,c): print("test--",a+b+c) @time_fun_pre("mark_test2") def test2(a,b,c): return a+b+c test(1,2,3) print(test2(1,2,3)) #休眠3秒 sleep(3) test(1,2,3) print(test2(3,4,5))
結果:
test 在 Wed Aug 15 22:43:27 2018 時被調用,pre參數爲:mark_test test-- 6 test2 在 Wed Aug 15 22:43:27 2018 時被調用,pre參數爲:mark_test2 6 test 在 Wed Aug 15 22:43:30 2018 時被調用,pre參數爲:mark_test test-- 6 test2 在 Wed Aug 15 22:43:30 2018 時被調用,pre參數爲:mark_test2 12
python類裝飾性必需要接受一個callable對象做爲參數,而後返回一個callable對象,在python中,通常callable對象都是函數,只要對象重寫了
__call__()方法,那麼這個對象就是callable對象。
實例:
class Test(): def __init__(self,func): print("test初始化:",func.__name__) self.func=func def __call__(self, *args, **kwargs): print("我調用了") self.func @Test def test(): print("--test--") test()
結果:
test初始化: test 我調用了