【问题标题】:Passing arguments to a decorator将参数传递给装饰器
【发布时间】:2014-11-17 18:14:07
【问题描述】:

我想将值列表传递给装饰器。装饰器装饰的每个函数都传递不同的值列表。我正在使用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'

我该怎么做?

【问题讨论】:

标签: python python-decorators


【解决方案1】:

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

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

【讨论】:

  • 这很酷。无论如何,这可以通过decorator 库来实现吗?
猜你喜欢
  • 2021-11-21
  • 2018-08-24
  • 2014-10-01
  • 1970-01-01
  • 2022-07-12
  • 2018-12-04
  • 2020-06-12
  • 1970-01-01
相关资源
最近更新 更多