2015-08-24 65 views
0

我读了这个伟大的职位:How to make a chain of function decorators?Python - 如何创建一个带参数的新装饰函数?

我决定摆弄它,我服用此块从它:

# 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的所以请原谅我,如果我错过了一些非常明显的在这里。

+1

不及格'first_name'和'last_name'上线11 –

回答

1

它应该具有:

decorated_print_full_name = a_decorator_passing_arguments(print_full_name) 
+0

是的,我是个白痴。我必须将该函数作为对象传递,而不是作为对象的调用。谢谢! – jktstance

+0

如果它没有失败,那么当包装器尝试调用'None(arg1,arg2)'时,它会后者失败。 –

相关问题