Python - 如何创建一个带参数的新装饰函数?

时间:2015-08-24 21:08:42

标签: python python-decorators

我已经阅读了这篇精彩帖子:How to make a chain of function decorators?

我决定摆弄它,我正在接受它:

# 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),该怎么办?基本上,我对如何更改代码更加好奇,所以 不要 使用@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的新手,所以如果我错过了一些非常明显的东西,请原谅我。

0 个答案:

没有答案