python-装饰器案例1
高阶函数+嵌套函数=装饰器
例1:
import time def timer(func): def deco(): start_time=time.time() func() stop_time=time.time() print("kezi the %s"%(stop_time-start_time)) return deco @timer def test1(): time.sleep(3) print ("in the test1") @timer def test2(): time.sleep(3) print("in the test2") #test1=timer(test1)=@timer test1() #test2=timer(test2)=@timer test2() 打印结果 in the test1 kezi the 3.0000288486480713 in the test2 kezi the 3.0009706020355225
例2 代参数的装饰
import time def timer(func): def deco(*arg1,**age2): start_time=time.time() func(*arg1,**age2) stop_time=time.time() print("kezi the %s"%(stop_time-start_time)) return deco @timer def test1(): time.sleep(3) print ("in the test1") @timer def test2(): time.sleep(3) print("in the test2") @timer def test3(name,age): time.sleep(3) print("in the test3:",name,age) # #test1=timer(test1)=@timer test1() # # #test2=timer(test2)=@timer test2() test3("kezi",33) 打印结果 in the test1 kezi the 3.00183367729187 in the test2 kezi the 3.0006985664367676 in the test3: kezi 33 kezi the 3.000452756881714