python装饰器顺序

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!
复制代码

 

 

posted on   mlllily  阅读(35)  评论(0编辑  收藏  举报

相关博文:
阅读排行:
· TypeScript + Deepseek 打造卜卦网站:技术与玄学的结合
· Manus的开源复刻OpenManus初探
· .NET Core 中如何实现缓存的预热?
· 三行代码完成国际化适配,妙~啊~
· 阿里巴巴 QwQ-32B真的超越了 DeepSeek R-1吗?
< 2025年3月 >
23 24 25 26 27 28 1
2 3 4 5 6 7 8
9 10 11 12 13 14 15
16 17 18 19 20 21 22
23 24 25 26 27 28 29
30 31 1 2 3 4 5

统计

点击右上角即可分享
微信分享提示