Python 類裝飾器
阿新 • • 發佈:2018-12-14
1.
import time, datetime class Ly: def __init__(self, fun): self.fun = fun print('this is the first step on ' + str(datetime.datetime.now())) time.sleep(1) self.fun() def __call__(self): print('this is the thirty step on ' + str(datetime.datetime.now())) time.sleep(1) @Ly def show(): print('this is the second step on ' + str(datetime.datetime.now())) time.sleep(1) if __name__ == "__main__": show() print('this is the fourth step on ' + str(datetime.datetime.now()))
2.
import time class Ly(object): def __init__(self, fun): print("this is the first step") time.sleep(1) self.fun = fun def __call__(self, *args): print("this is the second step") time.sleep(1) self.fun(*args) print("this is the fourth step") time.sleep(1) @Ly def show(a1, a2, a3, a4): print('this is the thirty step', a1, a2, a3, a4) time.sleep(1) show("parm", "1", "1", "1") print("After first part call") time.sleep(1) show("parm", "2", "2", "2") print("After second part call")
從中可以發現:
(1).只要有被類裝飾器裝飾的物件,類裝飾器的 __init__ 函式就會執行(不需要呼叫)
(2).被類裝飾器裝飾的函式不論被呼叫幾次,__init__ 函式只會執行一次,並且它的執行是被裝飾函式宣告裝飾時就自動執行,不需要手動呼叫
(3).當被裝飾函式存在引數時,從 __call__ 函式傳進引數(不必須 *args,但這是一種規範 def __call__(self,*args,**kwargs))
*args是指字串,**kwargs是指字典
3.
import time class Ly: def __init__(self, one_parm, two_parm, three_parm): self.one_parm = one_parm self.two_parm = two_parm self.three_parm = three_parm def __call__(self, fun): print('性別為' + self.one_parm + "的" + self.two_parm + "歲的" + self.three_parm) time.sleep(1) def info(*args): fun(*args) return info @Ly("男", "22", "ly") def show(name, age, sex): print('性別為' + sex + "的" + age + "歲的" + name) show("藍月", "20", "男")
注意:
(1).裝飾器有裝飾器的引數,函式(被裝飾器修飾的函式)有函式的引數,不可混淆
(2).的引數從 __init__ 函式中傳,函式的引數從 __call__ 函式中傳