使用函数装饰装饰器 - 为什么以下不起作用?

问题描述 投票:0回答:1

我很难理解装饰者的以下行为 - 有人可以帮助我吗?

基本上,我有一个

decorator_for_decorator
函数来装饰装饰器:

def decorator_for_decorator(func):
    def wrapper(*args):
        print('Decorator successfully decorated')
        return func(*args)
    return wrapper

当我这样装饰我的装饰器时:

# this doesn't work
@decorator_for_decorator
def decorator(func):
    def wrapper(*args):
        print('Function successfully decorated')
        return func(*args)
    return wrapper

def apply_decorator(func):
    func = decorator(func)
    return func

def f1():
    print('hello')

f2 = apply_decorator(f1)

f2()

对 f2() 的调用返回:

Function successfully decorated
hello

表明decorator_for_decorator没有装饰我的装饰器。但是,如果我像这样装饰我的装饰器:

# this works
def decorator(func):
    @decorator_for_decorator
    def wrapper(*args):
        print('Function successfully decorated')
        return func(*args)
    return wrapper

f2 = apply_decorator(f1)

f2()

调用 f2() 返回:

Decorator successfully decorated
Function successfully decorated
hello

为什么会这样?我希望装饰装饰器的两种方法都可以工作,但似乎只有后者有效。

python python-3.x decorator python-decorators
1个回答
0
投票

你的装饰师装饰得很好。你的“第二级”

decorator_for_decorator
以这样的方式装饰“第一级”装饰器,当“第一级”装饰器运行时,它会打印
Decorator successfully decorated

该消息是在“第一级”装饰器运行时打印的,而不是在装饰器被装饰时打印,或者在底层函数

f1
运行时打印。

© www.soinside.com 2019 - 2024. All rights reserved.