将参数传递给装饰器

时间:2014-09-23 13:46:19

标签: python python-decorators

我想将值列表传递给装饰器。由装饰器装饰的每个函数都传递不同的值列表。我正在使用decorator python库

以下是我的尝试 -

from decorator import decorator
def dec(func, *args):
     // Do something with the *args - I guess *args contains the arguments
     return func()

dec = decorator(dec)

@dec(['first_name', 'last_name'])
def my_function_1():
    // Do whatever needs to be done

@dec(['email', 'zip'])
def my_function_2():
    // Do whatever needs to be done

然而,这不起作用。它会出错 - AttributeError: 'list' object has no attribute 'func_globals'

我该怎么做?

1 个答案:

答案 0 :(得分:0)

您可以在没有装饰器库的情况下实现它

def custom_decorator(*args, **kwargs):
    # process decorator params
    def wrapper(func):
        def dec(*args, **kwargs):
            return func(*args, **kwargs)
        return dec
    return wrapper

@custom_decorator(['first_name', 'last_name'])
def my_function_1():
    pass
@custom_decorator(['email', 'zip'])
def my_function_2():
    pass