有如下代码:
def decorator_a(func):
print('Get in decorator_a')
def inner_a(*args, **kwargs):
print('Get in inner_a')
func(*args, **kwargs)
print("get in outer_a")
return inner_a
def decorator_b(func):
print('Get in decorator_b')
def inner_b(*args, **kwargs):
print('Get in inner_b')
func(*args, **kwargs)
print("get in outer_b")
return inner_b
@decorator_b
@decorator_a
def f():
print('Get in f')
f()
执行的结果如下:
Get in decorator_a
Get in decorator_b
Get in inner_b
Get in inner_a
Get in f
get in outer_a
get in outer_b
多个装饰器函数同时装饰一个函数时,依照以下原则进行:
1、装饰器函数在被定义的装饰器函数定义好后立即执行。
也就是说, print(‘Get in decorator_a’)和print(‘Get in decorator_b’)在定义装饰器函数中会被立即执行掉。
2、装饰器调用时,从上到下分别调用,执行到被装饰函数时,会跳转至下一装饰器执行后再执行被装饰函数,最后执行最上面的装饰器。
上述执行的顺序为:
decorate_b(print(‘Get in inner_b’))→***decorate_a***(print(‘Get in inner_a’))→***func***→***decorator_a***(print(“get in outer_a”))→***decorate_b***(print(“get in outer_b”))