Python装饰器
1 #author F 2 3 #装饰器: 本质是函数 为其他函数添加功能 文章发表过程->前后添加->运营添加->... 4 #已经上线 100个函数用到 需要修改 5 #装饰器原则: 1.不能修改被装饰函数的代码 6 # 2.不能修改被装饰的函数的调用方式 7 #也即: 装饰器对被装饰函数是透明的 对被装饰函数完全不影响 8 9 import time 10 ''' 11 def timmer(func): 12 def warpper(*args, **kwargs): 13 start_time = time.time() 14 func() 15 stop_time = time.time() 16 print("the func run time is %s" %(stop_time-start_time)) 17 return warpper 18 19 @timmer 20 def test1(): 21 time.sleep(3) 22 print("in the test 1") 23 24 25 # test1() 26 27 #装饰器需要的认识 28 #1.*函数即变量* __匿名函数 29 #2.高阶函数 30 # a:把一个函数名当作实参传给另一个函数 (在不修改被装饰函数源代码的情况下为其添加功能) 31 # b:返回值中包含函数名 (不修改函数的调用方式) 32 #3.函数嵌套 33 #高阶函数+函数嵌套 -> 装饰器 34 #函数在使用过程中分为两步: 第一是定义 第二是调用 35 36 37 #怎么写一个高阶函数? 38 # 1.写一个形参 39 # 2.函数当作实参传入 40 41 def bar(): 42 print("in the bar") 43 44 45 def test2(func): 46 print(func) 47 48 # test2(bar) #打印函数所在的内存地址 49 50 #在返回值中包含函数 51 52 53 def barr(): 54 time.sleep(1) 55 print("in the barr") 56 57 58 def test3(func): 59 print(func) #打印函数的返回地址 60 return func #返回函数的内存地址 61 62 # print(test3(barr)) #区别 test3(barr) 和 test3(barr()) 前者传的是函数的地址 后者传递的是函数的返回值 63 # t = test3(barr) #返回barr的地址 64 # t() #调用地址 运行函数 65 66 #嵌套函数 67 #在函数体内再次定义另一个函数 注意和函数调用的区别 68 def foo(): 69 print("in the foo") 70 def bara(): 71 print("in the bar") 72 #bara() #无法调用 函数的 局部特性 73 bara() 74 foo() 75 #注意函数的嵌套和函数的调用的区别: 76 # def test_1(): 77 # test_2() #这个是函数的调用 不是函数的嵌套 78 ''' 79 80 #######################################装饰器######################################## 81 #step1: 82 # def deco(func): 83 # start_time = time.time() 84 # func() 85 # stop_time = time.time() 86 # print("the function cost %s" %(stop_time-start_time)) 87 88 #step2: 89 # def deco(func): 90 # start_time = time.time() 91 # return func 92 # stop_time = time.time() 93 # print("the function cost %s" %(stop_time-start_time)) 94 95 #step3 96 def timer(func): 97 def deco(): 98 start_time = time.time() 99 func() 100 stop_time = time.time() 101 print("the function cost %s" %(stop_time-start_time)) 102 return deco 103 104 @timer 105 def test1(): 106 time.sleep(1) 107 print('in the test1') 108 @timer 109 def test2(): 110 time.sleep(2) 111 print('in the test2') 112 113 # test1() 114 # test2() 115 116 #step1: 不修改函数的源代码 添加新功能 117 # deco(test1) 118 # deco(test2) 119 120 #step2: 不修改函数的调用方式 但没有完成新功能 121 # test1 = deco(test1) 122 # test2 = deco(test2) 123 # test1() 124 # test2() 125 126 #step3: 函数嵌套整合两者 127 # test1 = timer(test1) 128 # test2 = timer(test2) 129 # test1() 130 # test2() 131 132 test1() 133 test2() 134 135 #自我总结: 装饰器其实是把被装饰函数放到一个装饰用的函数中加工处理 然后在这个装饰函数外层包裹一个函数 用来返回这个装饰函数的地址