標籤:return 附加 代碼 nbsp 方式 無法 本質 stop sleep
1.裝飾器
定義:本質是函數,就是為其他函數添加附加功能
原則:1.不能修改被裝飾的函數的原始碼
2.不能修改被裝飾的函數的調用方式
例子:
import timedef timer(func): def warpper(*args,**kwargs): start_time = time.time() func() stop_time = time.time() print("the func run time is %s" % (stop_time-start_time)) return warpper@timer #實際功能相當於func1 = timer(func1)def func1(): time.sleep(3) print("in the test1")func1()#結果#in the test1#the func run time is 3.0005111694335938
該函數滿足裝飾器的所有要求
裝飾器=高階函數+嵌套函數
高階函數:
把一個函數名當做實參傳給另外一個函數;傳回值中包含函數名
def func1(func): print(func)def func2(): print(1)func1(func2)
嵌套函數:
在一個函數的函數體內定義另一個函數
def func1(): print("in the func1") def func2(): print("in the func2") func2()func1()
我的理解:
裝飾器的實現方式,本質就是改變原函數的記憶體位址。通過高階函數的傳回值,將嵌套函數的記憶體位址賦給了原函數,而原函數的功能被記錄在了嵌套函數中,通過嵌套函數添加了新功能,而且不改變原始碼及原函數的調用方式。func1函數實際上已經變成了warpper函數,warpper函數的功能=func1原來的功能+添加的功能。但是func1的功能將會被永遠改變,無法再單獨實現func1的功能。
那如果函數要傳參數進去怎麼辦呢?
簡單!加個非固定參數就搞定了!
import timedef timer(func): def warpper(*args, **kwargs): start_time = time.time() func(*args, **kwargs) stop_time = time.time() print("the func run time is %s" % (stop_time - start_time)) return warpper@timerdef func1(): time.sleep(1) print("in the test1")@timerdef func2(*args, **kwargs): print(args, kwargs)func1()func2("Nick", daizhi="22", sex="male")
Step4 - Python基礎4 迭代器、裝飾器、軟體開發規範