您好,登錄后才能下訂單哦!
本文實例講述了Python3.5裝飾器。分享給大家供大家參考,具體如下:
#!/usr/bin/env python # -*- coding:utf-8 -*- # Author:ZhengzhengLiu #高階函數+嵌套函數==>裝飾器 import time def timer(func): #timer(test1)-->func=test1 def decor(): start_time = time.time() func() #run test1 stop_time = time.time() print("the run time of func is %s" %(stop_time-start_time)) return decor @timer #test1 = timer(test1) def test1(): time.sleep(3) print("in the test1") @timer #test2 = timer(test2) def test2(): time.sleep(3) print("in the test2") print(timer(test1)) #打印deco的地址 #test1 = timer(test1) #test2 = timer(test2) test1() #-->執行decor test2()
運行結果:
<function timer.<locals>.decor at 0x00B720C0>
in the test1
the run time of func is 3.000171661376953
in the test2
the run time of func is 3.000171661376953
1、裝飾器修飾有參數函數
#高階函數+嵌套函數==>裝飾器 import time def timer(func): #timer(test1)-->func=test1 def decor(arg1,arg2): start_time = time.time() func(arg1,arg2) #run test2 stop_time = time.time() print("the run time of func is %s" %(stop_time-start_time)) return decor @timer #test2 = timer(test2) = decor test2(name)==>decor(name) def test2(name,age): print("test2:",name,age) test2("liu",23)
運行結果 :
test2: liu 23
the run time of func is 0.0
2、裝飾器修飾多個函數,有的函數帶參數,有的函數不帶參數的情況(采用參數組)
#高階函數+嵌套函數==>裝飾器 import time def timer(func): #timer(test1)-->func=test1 def decor(*args,**kwargs): start_time = time.time() func(*args,**kwargs) #run test1 stop_time = time.time() print("the run time of func is %s" %(stop_time-start_time)) return decor @timer #test1 = timer(test1) def test1(): time.sleep(3) print("in the test1") @timer #test2 = timer(test2) = decor test2(name)==>decor(name) def test2(name,age): time.sleep(1) print("test2:",name,age) #test1 = timer(test1) #test2 = timer(test2) test1() #-->執行decor test2("liu",23)
運行結果:
in the test1
the run time of func is 3.0036065578460693
test2: liu 23
the run time of func is 1.0084023475646973
更多關于Python相關內容可查看本站專題:《Python數據結構與算法教程》、《Python Socket編程技巧總結》、《Python函數使用技巧總結》、《Python字符串操作技巧匯總》及《Python入門與進階經典教程》
希望本文所述對大家Python程序設計有所幫助。
免責聲明:本站發布的內容(圖片、視頻和文字)以原創、轉載和分享為主,文章觀點不代表本網站立場,如果涉及侵權請聯系站長郵箱:is@yisu.com進行舉報,并提供相關證據,一經查實,將立刻刪除涉嫌侵權內容。