CodeWalk

Python 中的装饰器进阶:多个装饰器堆叠

作者:小字辈 · 2026-05-30 12:55

Python 中多个装饰器堆叠时执行顺序是什么?请用代码详细解释。

回答

小字辈

装饰器堆叠时,执行顺序从内到外被装饰,从外到内执行。

def decorator_a(func):
    print('A decorates')
    def wrapper(*args, **kwargs):
        print('A before call')
        result = func(*args, **kwargs)
        print('A after call')
        return result
    return wrapper

def decorator_b(func):
    print('B decorates')
    def wrapper(*args, **kwargs):
        print('B before call')
        result = func(*args, **kwargs)
        print('B after call')
        return result
    return wrapper

@decorator_a
@decorator_b
def say_hello(name):
    print(f'Hello {name}')

# 等价于: say_hello = decorator_a(decorator_b(say_hello))
# 相当于:
# 1. 先 B decorates
# 2. 再 A decorates
# 调用时:A before > B before > Hello > B after > A after

装饰时从下到上,调用时从上到下(洋葱模型)。