python中有趣的裝飾器
阿新 • • 發佈:2021-10-07
在函式上新增一個裝飾器,增加額外的操作處理(比如日誌、計時等)。
特別是在程式碼除錯階段特別好用。
import time from functools import wraps def funcruntime(func): @wraps(func) def wrapper(*args, **kwargs): start = time.time() result = func(*args, **kwargs) end = time.time() print(func.__name__, end-start) return result return wrapper
簡單的時間裝飾器。
注:這裡特別要注意的是需要匯入functools裡@wraps裝飾器來註解底層包裝函式。非常重要,不然原來的函式裡的元資訊比如名字、文件字串、註解和引數簽名都丟失了。其實任何裝飾器操作需要保留元資料都應該使用這個@wraps裝飾器,甚至我覺得這個就應該無腦用。
@funcruntime def testtime(t: int): """ 測試裝飾器效果 :param t: int :return: None """ time.sleep(t) return testtime(1)
執行效果如下:
這樣一個簡單的測試方法的裝飾器就完成了。
裝飾器其實就是把func直接當做引數傳入做了一個閉包處理。
def testtime(t: int): """ 測試裝飾器效果 :param t: int :return: None """ time.sleep(t) return testtime = funcruntime(testtime) testtime(1)
這段程式碼和上面是完全等價的。
注:內建的裝飾器@staticmethod,@classmethod,@property
原理也是一樣的。