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

Python decorators. Error while passing arguments

我正在努力研究装饰器。 所以我尝试将参数传递给装饰器并在装饰器函数中处理它们。 我只是将一个列表传递给装饰器,并希望在调用后在装饰器函数中处理我的列表 原来的功能。这是我的代码

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

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

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