Python装饰器。传递参数时出错

时间:2015-06-17 07:31:44

标签: python python-decorators

我试图围绕装饰者。 所以我尝试将参数传递给装饰器并在装饰器函数内处理它们。 我只是将一个列表传递给装饰器,并希望我的列表在调用后在装饰器函数内处理 原来的功能。这是我的代码

def decorator_function(original_function):
    def new_function(*args, **kwargs):
        print("Your list shall be processed now.")
        print args
        #Do something with the passed list here.Say, call a function Process(list,string)
        original_function(*args, **kwargs) 
    return new_function



@decorator_function([1,2,3])
def hello(name = None):
    if name == None:
        print "You are nameless?"
    else:
        print "hello there,",name

hello("Mellow")

我收到此错误

Your list shall be processed now.
(<function hello at 0x7f9164655758>,)
Traceback (most recent call last):
  File "anno_game.py", line 14, in <module>
    def hello(name = None):
  File "anno_game.py", line 8, in new_function
    original_function(*args, **kwargs) 
TypeError: 'list' object is not callable

任何人都可以告诉我,我在这里搞砸了什么并指出了我正确的方向?

1 个答案:

答案 0 :(得分:1)

def decorator_function(original_function):
    def new_function(*args, **kwargs):
        print("Your list shall be processed now.")
        print args
        #Do something with the passed list here.Say, call a function Process(list,string)
        original_function(*args, **kwargs) 
    return new_function

@decorator_function([1,2,3])
def hello(name = None):
    if name == None:
        print "You are nameless?"
    else:
        print "hello there,",name

hello("Mellow")

@decorator_function([1,2,3]) decorator_function被调用[1,2,3]作为original_function参数传递给它时,您试图调用original_function(*args, **kwargs)

要让装饰器接收列表,您需要制作另一个包装器:

def decorator_function(a_list):

        print("Your list shall be processed now.", a_list)
        #Do something with the passed list here.Say, call a function Process(a_list)

    def wrapper(original_function):

        def new_function(*args, **kwargs):

            print("Your list with function args shall be processed now.", a_list, args)
            #Do something with the passed list here.  Say, call a function Process(a_list, args)

            original_function(*args, **kwargs) 

        return new_function

    return wrapper