python装饰器顺序

发布时间 2023-10-08 16:28:22作者: mlllily

Python的装饰器是应用的函数或方法的特殊类型改变,它们会在被装饰的函数或方法被调用时执行。你可以使用多个装饰器来装饰一个函数,装饰器的执行顺序与它们应用的顺序有关

# 使用两个装饰器装饰一个函数
@decorator1
@decorator2
def func():
    pass

在上述代码中,首先应用的装饰器是decorator2,然后应用的装饰器是decorator1。可以这样理解,当你调用func()时,首先执行装饰器 decorator2 对 func 进行装饰,然后执行装饰器 decorator1 对已经被 decorator2 装饰过的 func 进行装饰。

也就是说装饰器的顺序是从下到上(也就是说,最接近函数定义的装饰器最先被应用),或者你可以将其视为从内到外(也就是说,最接近函数定义的装饰器最先被应用)。

下面是一个具体示例,理解装饰器顺序:

def decorator1(func):
    def wrapper():
        print("Executing decorator1")
        func()
    return wrapper

def decorator2(func):
    def wrapper():
        print("Executing decorator2")
        func()
    return wrapper

@decorator1
@decorator2
def hello_world():
    print("Hello, world!")

hello_world()

# 输出:
# Executing decorator1
# Executing decorator2
# Hello, world!