1. 程式人生 > >裝飾器中使用args

裝飾器中使用args

name 匹配 code imp 使用 logs 沒有 typeerror pri

 1 import time
 2 
 3 def timer(func):
 4     #def deco():  #part1
 5     #def deco(arg1):   #part2
 6     def deco(*args,**kwargs):   #part3
 7         start_time=time.time()
 8         #func()   #part1
 9         #func(arg1)   #part2, 這裏帶了參數會影響到test1(),因為test1()裏面沒有參數
10         func(*args,**kwargs)    #
part3,test1()沒有參數不影響,*args可以匹配空參數 11 stop_time=time.time() 12 print(the time of the function running is %s%(stop_time-start_time)) 13 return deco 14 15 @timer 16 def test1(): 17 time.sleep(1) 18 print(this is test1) 19 20 @timer 21 def test2(name): #給test2加一個形參, test2=timer(test2)=func, test2裏面有參數,func應該也要加參數
22 time.sleep(1) 23 print(this is test2,name) 24 25 #test1() #part2 26 test1() #part1, part3 27 test2(alex) #從錯誤可以看到test2()=deco() test2給了實參,deco()裏面也必須要給個參數 28 #TypeError: deco() takes 0 positional arguments but 1 was given 29 30 #part3結果 31 # this is test1 32 # the time of the function running is 1.0000574588775635
33 # this is test2 alex 34 # the time of the function running is 1.0000569820404053

裝飾器中使用args