首页 > 代码库 > 装饰器中使用args

装饰器中使用args

 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