Functools.update_wrapper()无法正常工作 [英] Functools.update_wrapper() doesn't work properly

查看:105
本文介绍了Functools.update_wrapper()无法正常工作的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在装饰器中使用了Functools.update_wrapper(),但是update_wrapper似乎仅重写了函数属性(例如__doc____name__),但对help()函数没有影响.

I use Functools.update_wrapper() in my decorator, but It seems like update_wrapper rewrites only function attributes (such as __doc__, __name__), but does not affect on help() function.

我知道这些答案,但它们没有使用装饰器类.

I aware of these answers, but they don't work with decorator-class.

这是我的职责.

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

这是输出

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

它看起来像个错误,但是我该如何解决?

It looks like a bug, but how can I fix it?

推荐答案

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

functools.update_wrapper() sets the attribute on the instance, but help() looks at the information on the type.

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

So printer.__doc__ gives you the instance attribute, help() prints information about type(printer), e.g. the memoized class, which does not have a __doc__ attribute.

这不是错误,这完全是设计使然;当您传入实例时, help()始终会查看该类.如果要help()用于装饰函数,请不要使用类作为装饰器.

This is not a bug, this is all by design; help() will always look at the class when you pass in an instance. Don't use a class as decorator if you want help() to work for the decorated function.

这篇关于Functools.update_wrapper()无法正常工作的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆