多个装饰器执行顺序
多个装饰器执行顺序
from functools import wraps
def decorator_a(func):
print('Get in decorator_a')
@wraps(func)
def inner_a(*args, **kwargs):
print('Get in inner_a')
return func(*args, **kwargs)
return inner_a
def decorator_b(func):
print('Get in decorator_b')
@wraps(func)
def inner_b(*args, **kwargs):
print('Get in inner_b')
return func(*args, **kwargs)
return inner_b
@decorator_b # f = decorator_b(f) 此时 f = decorator_b(inner_a) = inner_b
@decorator_a # f = decorator_a(f) 此时 f = inner_a
def f(x):
print('Get in f')
return x * 2
f(1) # inner_b(1) ----> inner_a(1)
解析
"""
@decorator_a
def f(x):
print('Get in f')
return x * 2
# 相当于
def f(x):
print('Get in f')
return x * 2
f = decorator_a(f)
"""
执行顺序
"""
执行顺序
Get in decorator_a
Get in decorator_b
Get in inner_b
Get in inner_a
Get in f
"""
希望你眼眸有星辰,心中有山海,从此以梦为马,不负韶华