Python - 如何创建一个接受参数的新修饰函数?

Python - how do I create a new decorated function that takes arguments?

我读完了这篇很棒的文章 post:How to make a chain of function decorators?

我决定 fiddle 使用它并且我正在使用它的这个块:

# It’s not black magic, you just have to let the wrapper 
# pass the argument:

def a_decorator_passing_arguments(function_to_decorate):
    def a_wrapper_accepting_arguments(arg1, arg2):
        print "I got args! Look:", arg1, arg2
        function_to_decorate(arg1, arg2)
    return a_wrapper_accepting_arguments

# Since when you are calling the function returned by the decorator, you are
# calling the wrapper, passing arguments to the wrapper will let it pass them to 
# the decorated function

@a_decorator_passing_arguments
def print_full_name(first_name, last_name):
    print "My name is", first_name, last_name

print_full_name("Peter", "Venkman")
# outputs:
#I got args! Look: Peter Venkman
#My name is Peter Venkman

如果我不想将修饰后的 print_full_name(first_name, last_name) 重命名为它自己,而是想将修饰后的版本另存为不同的函数名称,例如 decorated_print_full_name(first_name, last_name),会怎样?基本上,我更好奇如何更改代码,所以我 DON'T 使用 @a_decorator_passing_arguments 快捷方式。

我重写了上面的内容(针对Python 3):

def a_decorator_passing_arguments(function_to_decorate):
    def a_wrapper_accepting_arguments(arg1, arg2):
        print("I got args! Look:", arg1, arg2)
        function_to_decorate(arg1, arg2)
    return a_wrapper_accepting_arguments

#@a_decorator_passing_arguments
def print_full_name(first_name, last_name):
    print("My name is", first_name, last_name)

decorated_print_full_name = a_decorator_passing_arguments(print_full_name(first_name, last_name))

decorated_print_full_name("Peter", "Venkman")

但是 Python 抱怨 first_name 没有在第 11 行定义。我对 Python 还是个新手所以如果我在这里遗漏了一些非常明显的东西请原谅我。

它应该适用于:

decorated_print_full_name = a_decorator_passing_arguments(print_full_name)