创建一个decorator依赖于kwargs参数作为参数

2024-04-26 11:16:38 发布

您现在位置:Python中文网/ 问答频道 /正文

我有个密码:

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()

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

^{pr2}$

Tags: name参数returnexamplemydefargsfunction
1条回答
网友
1楼 · 发布于 2024-04-26 11:16:38

您可以通过以下方式为decorator提供单独的参数:

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!')

运行此命令将生成以下输出:

^{pr2}$

还请注意,如果需要,还可以从wrapper和{}访问{}。在

相关问题 更多 >