【问题标题】:Python argumented decorator functionPython 带参数的装饰器函数
【发布时间】:2019-04-03 21:15:10
【问题描述】:

我有这个例子:

def decorator_function_with_arguments(arg1, arg2, arg3):
    def wrap(f):
        print("Inside wrap")
        def wrapped_f(*args):
            print("Pre")
            print("Decorator arguments:", arg1, arg2, arg3)
            f(*args)
            print("Post")
        return wrapped_f
    return wrap

@decorator_function_with_arguments("hello", "world", 42)
def sayHello(a1, a2, a3, a4):
    print('sayHello arguments:', a1, a2, a3, a4)

sayHello("say", "hello", "argument", "list")

输出是:

Inside wrap Pre Decorator arguments: hello world 42 sayHello arguments: say hello argument list Post

我对此的解释如下:decorator_function_with_arguments 得到它的 3 个参数。它输出一个函数(wrap),它接收一个函数并输出一个函数,这就是装饰的目的。所以现在wrap 将被执行(“Inside wrap”被打印出来),装饰发生了,wrapsayHello 放入wrapped_f,我们返回。现在,如果我打电话给sayHello,它将是它的包装版本,因此其余部分将被打印出来。好的,但是现在如果我写这个:

def argumented_decor(dec_arg1):
    def actual_decor(old_func):
        print("Pre Wrapped")
        def wrapped():
            print("Pre Main")
            print(dec_arg1)
            old_func()
            print("Post Main")
        return actual_decor
    return actual_decor

@argumented_decor("Decor Argument")
def f2():
    print("Main")

f2()

调用f2 时,我收到错误消息: TypeError: actual_decor() missing 1 required positional argument: 'old_func'

为什么? argumented_decor 得到它的参数,actual_decor 将被执行,“预包装”将被打印,f2 将被包装。现在,如果我调用它,它应该作为最内部的wrapped 函数。为什么不?我希望我可以理解地问我的问题。谢谢!

【问题讨论】:

  • print("Post Main")之后应该是return wrapped而不是return actual_decor

标签: python python-decorators


【解决方案1】:

您的actual_decor 函数在它应该返回包装函数wrapped 时返回自身:

def argumented_decor(dec_arg1):
    def actual_decor(old_func):
        print("Pre Wrapped")
        def wrapped():
            print("Pre Main")
            print(dec_arg1)
            old_func()
            print("Post Main")
        return wrapped
    return actual_decor

【讨论】:

  • 我才意识到,多么尴尬……至少这个问题显示了装饰器是如何工作的。谢谢
猜你喜欢
  • 2014-07-21
  • 2015-10-19
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2012-03-03
  • 2014-03-24
  • 1970-01-01
  • 2016-09-27
相关资源
最近更新 更多