標籤:標準 添加 war int *args 函數 等價 功能 return
使用情境:
思考這樣一個問題:對於生產系統,如何在修改最小,實現對原有模組添加新的功能呢?!通過裝飾器,即可完成這一目標。
裝飾器有兩個標準:
1、不修改原有代碼及原有調用方式;
2、可以增加新的功能;
例如,我們有一個方法func1,在這個方法中,列印兩條資訊並sleep 1秒鐘。
def func1(): print("this is in the func1 methord") time.sleep(1) print("exec the func1 finished")
‘‘‘調用方法‘‘‘ if __name__ == "__main__": func1()
|
現在我想不修改func1()方法及其調用方式的前提下,增加一個列印目前時間的功能,如何?呢?
import time
def timmer(func):#定義裝飾器timmer def decotator(*args,**kwargs):#定義高階函數 print("this is in the decorator,and current time is %s",args,kwargs)#添加的方法 func(*args,**kwargs)#執行傳遞變數的方法 return decotator#另其返回高階函數地址
@timmer#指明裝飾器為timmer,等價於func1=timmer(func1) def func1(): print("this is in the func1 methord") time.sleep(1) print("exec the func1 finished")
@timmer def func2(name): print("this is in the func2 methord,and the name is :%s" %name) time.sleep(1) print("exec the func2 finished")
#調用func1方法 func1() |
學習整理--python裝飾器