在装饰器中使用时,Wraps会给出TypeError

时间:2017-06-01 07:22:21

标签: python python-3.x python-decorators

我创建了一个装饰器来打印它装饰的函数的名称并且它可以工作:

>>> def debug(func):
...    msg=func.__qualname__
...    def wrapper(*args, **kwargs):
...       print(msg)
...       return func(*args, **kwargs)
...    return wrapper
... 
>>> @debug
... def add(x, y):
...    return x+y
... 
>>> add(1,2)
add
3

现在我想将包装装饰器应用到包装器但是当我这样做时我得到了错误" TypeError:update_wrapper()获得了多个参数值'包装'"

>>> from functools import wraps
>>>
>>> def debug(func):
...    msg=func.__qualname__
...    @wraps
...    def wrapper(*args, **kwargs):
...       print(msg)
...       return func(*args, **kwargs)
...    return wrapper
... 
>>> @debug
... def add(x, y):
...    return x+y
... 
>>> add(1,2)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: update_wrapper() got multiple values for argument 'wrapped'
>>>

我做错了什么以及错误发生的原因?

1 个答案:

答案 0 :(得分:1)

知道了。对不起,问题是我使用了错误的装饰作为装饰。这是正确的代码

def debug(func):
   msg = func.__qualname__
   @wraps(func)
   def wrapper(*args, **kwargs):
      print(msg)
      return func(*args, **kwargs)
   return wrapper
相关问题