更詳細的裝飾器,真心實力推薦,里面介紹的很清楚,介紹可見鏈接:https://blog.csdn.net/buster_zr/article/details/81104551
1、裝飾器的理論:
(1)裝飾器實際上就是一個函數
(2)有2個特別之處,參數是一個函數。返回值是一個參數
2、裝飾器的簡單理解:
實際上就是為了給一個程序添加功能,但是該程序已經上線或者已被使用,那么就不能大批量的修改源碼,這樣不現實,因此就產生了裝飾器。
注意點:
(1)不能修改被裝飾的函數的源代碼
(2)不能修改被裝飾的函數的調用方式
3、裝飾器的組成方式:
函數+實參高階函數+返回值高階函數+嵌套函數+語法糖 = 裝飾器
有關高階函數的理解:
(1)把一個函數名當作實參傳給另外一個函數(”實參高階函數“)
(2)返回值中包含函數名(”返回值高階函數“)
嵌套函數的理解:
嵌套函數指的是在函數內部定義一個函數,而不是調用。
語法糖:
寫法:@xx ,一般寫在函數的上方
4、真正裝飾器的開始之處:
裝飾器在裝飾時,需要在每個函數前面加上@xxx
(1) 裝飾無參函數,示例代碼如下:
#裝飾器裝飾的函數無參數 def timer(func): #func其實指的就是test def deco(): start = time.time() func() #這里其實是對test的調用 stop = time.time() print (stop-start) return deco @timer #test函數使用裝飾器 def test(): time.sleep(2) print ("test is running") test() 打印結果: test is running 2.003510952
(2)裝飾有參函數,示例代碼如下:
#裝飾器裝飾的函數有參數 def timer(func): def deco(*args,**kwargs): #添加可變參數*args和**kwargs start = time.time() func(*args,**kwargs) #這里也是一樣,添加可變參數*args和**kwargs stop = time.time() print (stop-start) return deco @timer def test(value): #test函數有個參數value,正因為裝飾器timer裝飾的函數test有參數value,因此在timer中的有了可變參數 time.sleep(2) print ("test is running %s" %value) test("22") 打印結果: test is running 22
2.00424408913
3、帶參數的裝飾器,示例代碼如下:
#裝飾器帶參數 def timer(parameter): def out_wapper(func): def wapper(*wargs,**kwargs): if parameter == "task1": start = time.time() func(*wargs,**kwargs) stop = time.time() print ("the task1 is run:",stop-start) elif parameter == "task2": func(*wargs, **kwargs) print ("the task2 is run:") return wapper return out_wapper @timer(parameter = "task1") def task1(): time.sleep(2) print "in the task1" @timer(parameter = "task2") def task2(): time.sleep(2) print "in the task2" task1() task2()
打印結果:
in the task1
('the task1 is run:', 2.002906084060669)
in the task2
the task2 is run: