【问题标题】:Creating a decorator depends with the kwargs argument as parameters [duplicate]创建装饰器取决于使用 kwargs 参数作为参数[重复]
【发布时间】:2016-12-16 05:12:57
【问题描述】:

我有一个代码:

from functools import wraps

def my_decorator(f):
    @wraps(f)
    def wrapper(*args, **kwargs):
        print kwargs["name"] # Should display Dean Armada
        print 'Calling decorated function'
        return f(*args, **kwargs)
    return wrapper

@my_decorator(name="Dean Armada")
def example():
    """Docstring"""
    print 'Called example function'

example()

我想要实现的是让我的装饰器依赖 kwargs 参数作为它的所有参数。我上面的代码抛出了这个错误

my_decorator() got an unexpected keyword argument 'name'

【问题讨论】:

  • 创建另一个接受name 参数的(外)层,并将其传递给wrapper

标签: python python-decorators


【解决方案1】:

您可以通过以下方式为您的装饰器设置单独的参数:

from functools import wraps


def my_decorator(**decorator_kwargs):  # the decorator
    print decorator_kwargs['name']

    def wrapper(f):  # a wrapper for the function
        @wraps(f)
        def decorated_function(*args, **kwargs):  # the decorated function
            print 'Calling decorated function'
            return f(*args, **kwargs)
        return decorated_function
    return wrapper


@my_decorator(name='Dean Armada')
def example(string):
    print string


if __name__ == '__main__':
    example('Print this!')

运行它会产生输出:

Dean Armada
Calling decorated function
Print this!

另请注意,如果需要,wrapperdecorated_function 也可以访问decorator_kwargs

【讨论】:

    猜你喜欢
    • 2021-12-30
    • 2023-03-26
    • 2014-10-14
    • 2013-07-19
    • 2020-06-20
    • 1970-01-01
    • 2016-06-30
    • 1970-01-01
    相关资源
    最近更新 更多