0
点赞
收藏
分享

微信扫一扫

python 两个装饰器,怎么执行

在 Python 中,当你为一个函数应用多个装饰器时,它们会按照自下而上的顺序依次应用。具体来说,假设有两个装饰器 @decorator1@decorator2,应用到同一个函数 func 上,如下所示:

@decorator1
@decorator2
def func():
    pass

这等价于以下代码:

func = decorator1(decorator2(func))

也就是说,decorator2 先被应用,然后 decorator1 再被应用。下面是一个具体的例子来演示这种行为:

def decorator1(func):
    def wrapper(*args, **kwargs):
        print("Decorator 1: Before function execution")
        result = func(*args, **kwargs)
        print("Decorator 1: After function execution")
        return result
    return wrapper

def decorator2(func):
    def wrapper(*args, **kwargs):
        print("Decorator 2: Before function execution")
        result = func(*args, **kwargs)
        print("Decorator 2: After function execution")
        return result
    return wrapper

@decorator1
@decorator2
def say_hello():
    print("Hello, World!")

say_hello()

输出结果为:

Decorator 1: Before function execution
Decorator 2: Before function execution
Hello, World!
Decorator 2: After function execution
Decorator 1: After function execution

从输出可以看到,decorator2 首先包裹了原始函数 say_hello,然后 decorator1 又包裹了 decorator2 包裹后的函数。所以执行顺序是:

  1. decorator1 在函数执行前的代码。
  2. decorator2 在函数执行前的代码。
  3. 原始函数 say_hello 的代码。
  4. decorator2 在函数执行后的代码。
  5. decorator1 在函数执行后的代码。

总结:

  • 多个装饰器应用时,最内层的装饰器(最靠近函数的装饰器)最先执行,最外层的装饰器(最远离函数的装饰器)最后执行。
  • 装饰器的执行顺序为从内到外,返回顺序为从外到内。
举报

相关推荐

0 条评论