创建装饰器取决于kwargs参数作为参数

时间:2016-08-10 01:31:35

标签: python python-decorators

我有一个代码:

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'

1 个答案:

答案 0 :(得分:2)

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

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!

另请注意,如果需要,decorator_kwargswrapper也可以访问decorated_function