Functools.update_wrapper()无法正常工作

use*_*218 7 python decorator python-2.7 functools python-decorators

Functools.update_wrapper()在装饰器中使用,但似乎update_wrapper只重写函数属性(如__doc__,__name__),但不影响help()函数.

我知道这些答案,但它们不适用于装饰器类.

这是我的功能.

import functools

class memoized(object):

    def __init__(self, func):
        self.func = func
        functools.update_wrapper(self, func)

    def __call__(self, *args):
        self.func(*args)

@memoized 
def printer(arg):
    "This is my function"
    print arg
Run Code Online (Sandbox Code Playgroud)

这是输出

>>> printer.__doc__
This is my function

>>> help(printer)
Help on memoized in module __main__ object:

printer = class memoized(__builtin__.object)
 |  Methods defined here:
 |  
 |  __call__(self, *args)
 |  
 |  __init__(self, func)
 |  
 |  ----------------------------------------------------------------------
 |  Data descriptors defined here:
 |  
 |  __dict__
 |      dictionary for instance variables (if defined)
 |  
 |  __weakref__
 |      list of weak references to the object (if defined)
Run Code Online (Sandbox Code Playgroud)

它看起来像一个bug,但我该如何解决?

Mar*_*ers 12

functools.update_wrapper()在实例上设置属性,但help()查看类型的信息.

因此,printer.__doc__为您提供实例属性,help()打印有关的信息type(printer),例如memoized没有__doc__属性的类.

这不是一个错误,这完全是设计的; help()在传入实例时,它总是会查看该类.如果要help()使用装饰函数,请不要将类用作装饰器.

  • 我认为它已经破解了,因为使用类是一种标准方式,而且我是实现装饰器的最通用的方法.他们应该考虑的一个解决方法是使用`__helpobject__`魔术方法默认为`type(self)if notinstance(self,type)else self`,这将允许实现装饰器模式的类覆盖此方法. (4认同)