Functools.update_包装()无法正常工作

2024-04-27 00:00:11 发布

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

我在decorator中使用Functools.update_wrapper(),但似乎update_wrapper只重写函数属性(例如__doc____name__),但对{}函数没有影响。在

我知道these answers,但它们不适用于decorator类。在

这是我的职责。在

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

这是输出

^{pr2}$

它看起来像是个虫子,但我怎样才能修复它呢?在


Tags: 函数nameselfdoc属性defargargs
1条回答
网友
1楼 · 发布于 2024-04-27 00:00:11

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

因此,printer.__doc__提供了instance属性,help()打印关于type(printer)的信息,例如memoized类,它没有__doc__属性。在

这不是一个bug,这完全是设计的;^{} will always look at the class when you pass in an instance。如果希望help()为修饰函数工作,请不要将类用作装饰器。在

相关问题 更多 >