装饰器
装饰器是python语言中对于方法的一种包装形式,可以在不修改被装饰方法的前提下对该方法进行补充和修改,多重装饰器的使用顺序为:
装饰时顺序为从内到外,执行时从外到内
以如下代码为例
def decorator1(func):
print('before_decorated_1')
def wrapper1():
print('execute_decorator_1')
return func()
return wrapper
def decorator2(func):
print('before_decorated_2')
def wrapper2():
print('execute_decorator_2')
return func()
return wrapper
@decorator1
@decorator2
def test():
print('test result')
test()
如上代码的执行结果为:
before_decorated_2
before_decorated_1
execute_decorator_1
execute_decorator_2
test result
- 根据装饰器的定义,在执行test()的时候,如果存在装饰器便执行装饰器,所以优先执行decorator2装饰器
- 由于装饰器2的返回结果为执行至decorator2的内层函数时,根据装饰器定义装饰器实质上内层变成了decorator2(test)方法,而执行内层方法时仍会被上层的装饰器所影响,所以多重装饰器内层执行前装饰顺序会自内到外直至外层无装饰器为止
- 当从最外层开始执行wrapper()函数时,由于装饰器内层的多次wrapper函数封装,所以要执行到test函数实质上等价于执行为wrapper1(wrapper2)(),多层装饰可以类推出该顺序