1 #!/usr/bin/env python 2 # -*- coding:utf-8 -*- 3 # Author:woshinidaye 4 5 #装饰器:本质属于函数,语法:def,修饰其他函数,添加附加功能。 6 #类似于版本已经上线运行,现需要在版本中增加新功能,新特性且不能修改原版本文件。 7 #且原函数的调用方式不能被改变。 8 9 10 import time 11 # def decorator(func): 12 # def timer(): 13 # start_time = time.time() 14 # func() 15 # end_time = time.time() 16 # print('this function run time is %s' %(end_time-start_time)) 17 # return timer 18 # @decorator #test = decorator(test) 19 # def test(): 20 # time.sleep(2) 21 # print('this is a test function') 22 # # test = decorator(test) #test的内存地址就是decorator函数的返回值 23 # # test() 24 # test() 25 26 #刚才这个test函数没有参数,在运行时func()时不会报错,但是如果另一个函数,test2有一个参数,这个时候就会出错; 27 28 # def decorator(func): 29 # def timer(args1): 30 # start_time = time.time() 31 # func(args1) 32 # end_time = time.time() 33 # print('this function run time is %s' %(end_time-start_time)) 34 # return timer 35 # @decorator #test2 = decorator(test2) 36 # #把test2的内存地址传给decorator函数,decorator函数返回为timer的内存地址,那此时运行test2(’woshinidaye‘)就等于运行timer('woshinidaye'), 37 # #而最开始timer函数是没有变量的,所以会提示TypeError: timer() takes 0 positional arguments but 1 was given 38 # def test2(name): 39 # time.sleep(2) 40 # print('my name is %s' %name) 41 # 42 # # test2() #TypeError: test2() missing 1 required positional argument: 'name' 43 # test2('woshinidaye') #TypeError: timer() takes 0 positional arguments but 1 was given 44 45 #但是在timer函数固定了参数个数,岂不是只能对一个参数的函数装饰,没参数的或者有两个参数的函数都不能被装饰了。这就需要用到非固定参数了。 46 # def decorator(func): 47 # def timer(*args,**kwargs): 48 # start_time = time.time() 49 # func(*args,**kwargs) 50 # end_time = time.time() 51 # print('this function run time is %s' %(end_time-start_time)) 52 # return timer 53 # @decorator #test2 = decorator(test2) 54 # def test2(name): 55 # time.sleep(2) 56 # print('my name is %s' %name) 57 # @decorator 58 # def test(): 59 # time.sleep(2) 60 # print('this is a test function') 61 # @decorator 62 # def test3(x,y,z=3,*args,**kwargs): 63 # time.sleep(2) 64 # print(x,y) 65 # print(z) 66 # print(args) 67 # print(kwargs) 68 # test() 69 # test2('woshinidaye') 70 # test3(1,2,5,*[1,2,3],**{'name':'woshinidaye','age':13}) 71 72 def decorator(func): 73 def timer(*args,**kwargs): 74 start_time = time.time() 75 res = func(*args,**kwargs) 76 end_time = time.time() 77 print('this function run time is %s' %(end_time-start_time)) 78 return res 79 return timer 80 @decorator 81 def test4(): 82 time.sleep(2) 83 print('\033[032;1m in the func test4 \033[0m') 84 return '======>>> test4' 85 86 print(test4()) #装饰以前,test4()的返回结果是'======>>> test4' 87 # #装饰以后,返回结果为none,这是因为运行test4()其实是运行timer(),而timer并没有返回任何信息 88 89 90 # def test1(): 91 # print('in the test1') 92 # return test2() 93 # #return test2 两条命令是不一样的 94 # 95 # def test2(): 96 # print('in the test2') 97 # test1() 98 # print(test1())