装饰器
定义(本质是函数(def)装饰其他函数,为其他函数添加附加功能)
原则:不能修改被装饰函数的源代码
不能修改被装饰函数的调用方式
1 import time 2 3 def timeer(func): 4 def warpper(*args,**kwargs): 5 s_time = time.time() 6 func() 7 sp_time = time.time() 8 print("the func run time is %s" % (sp_time - s_time)) 9 return warpper 10 11 @timeer 12 13 def test1(): 14 time.sleep(1) 15 print("in the test1") 16 test1() # 装饰器没有修改原函数的调用方式 17 # 装饰器是一个函数 18 19 # ============================================================================= 20 # in the test1 21 # the func run time is 1.0009169578552246 22 # =============================================================================
装饰器的知识:
1.函数即变量
2.高阶函数
3.嵌套函数
高阶函数 + 嵌套函数 = 装饰器
#函数即变量 #python中的内存回收机制,没有变量名指向时。该内存被释放· # ============================================================================= #匿名函数 # zz = lambda x:x+3 # print(zz(3)) # #6 # # =============================================================================
对python逐行解释的补充
1 def te(): 2 print("in the te") 3 bar() 4 5 def bar(): 6 print("in the bar") 7 8 te() 9 10 #python j解释器逐行解释 11 # 先创建一个内存块,用te指向 然后创建内存块用bar指向。最后运行te()