Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/359.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python参数化装饰函数_Python_Python Decorators - Fatal编程技术网

Python参数化装饰函数

Python参数化装饰函数,python,python-decorators,Python,Python Decorators,我举了一个例子: 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)

我举了一个例子:

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")
输出为:

内包装
之前
装饰参数:hello world 42
sayHello参数:sayHello参数列表
发布

我的解释如下:带有参数的
decorator\u函数\u
获取其3个参数。它输出一个函数(
wrap
),该函数接收一个函数并输出一个函数,这是装饰的目的。现在将执行
wrap
(“内部包裹”打印),装饰发生,
wrap
接受
sayHello
并将其放入
wrapped\u 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\u decor()缺少1个必需的位置参数:“old\u func”


为什么?
argumented_decor
获取其参数,将执行
实际_decor
,“预包装”将被打印,
f2
将被包装。现在,如果我调用它,它应该作为最内部的
包装的
函数。为什么不呢?我希望我的问题可以理解。谢谢

当您的
实际装饰
函数应该返回包装函数
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

它应该是
return-wrapped
,而不是
return-react\u-decor
print(“Post-Main”)
之后。我刚刚意识到了这一点,多么尴尬。。。至少这个问题说明了装饰器是如何工作的。非常感谢。