1 def wrapper1(f1): 2 print('in wrapper1') 3 def inner1(*args,**kwargs): 4 print('in inner1') 5 ret = f1(*args,**kwargs) 6 print('111') 7 return ret 8 return inner1 9 10 def wrapper2(f2): 11 print('in wrapper2') 12 def inner2(*args,**kwargs): 13 print('in inner2') 14 ret = f2(*args,**kwargs) 15 print('222') 16 return ret 17 return inner2 18 19 def wrapper3(f3): 20 print('in wrapper3') 21 def inner3(*args,**kwargs): 22 print('in inner3') 23 ret = f3(*args,**kwargs) 24 print('333') 25 return ret 26 return inner3 27 28 @wrapper1 #3 func = wrapper1(func)即 func = wrapper2(inner2) -->f1 = inner2 -->打印in wrapper1 --> func = inner1 29 @wrapper2 #2 func = wrapper2(func)即 func = wrapper2(inner3) -->f2 = inner3 --> 打印in wrapper2 --> func = inner2 30 @wrapper3 #1 func = wrapper3(func) --> f3 = func -->打印in wrapper3 --> func = inner3 31 def func(): # 先执行离被装饰函数最近的那个装饰器 32 print('in func') 33 func() #4 func = inner1 34 #5 执行func() 即 执行inner1()-->打印in inner1 --> 执行f1()即执行inner2()-->打印in inner2-->执行f2()即执行inner3()-->打印in inner3--> 35 #6 -->执行f3()即执行func()-->打印in func-->打印333-->inner3执行完毕,返回到inner2-->打印222-->inner2执行完毕,返回到inner1--> 36 #7 -->打印111-->inner1执行完毕-->程序执行完毕 37 38 # 结果: 39 # in wrapper3 40 # in wrapper2 41 # in wrapper1 42 # in inner1 43 # in inner2 44 # in inner3 45 # in func 46 # 333 47 # 222 48 # 111 49 50 # 装饰器函数在被装饰函数定义好后立即执行。多个装饰器的调用顺序是自下往上的(装饰器装饰函数时的上下顺序)。 51 # 被装饰函数执行时,装饰器的执行顺序是从上往下的(装饰器装饰函数时的上下顺序,和装饰器函数定义顺序无关)。