I use Functools.update_wrapper()
在我的装饰器中,但看起来像update_wrapper
仅重写函数属性(例如__doc__
, __name__
),但不影响help()
功能。
我知道这些答案 https://stackoverflow.com/questions/23973783/python-decorator-with-arguments-of-decorated-function,但它们不适用于装饰器类。
这是我的功能。
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)
它看起来像一个错误,但我该如何修复它呢?
functools.update_wrapper()
设置属性在实例上,但在 Python 3.8 版本之前,help()
看资料在类型上.
So printer.__doc__
给你实例属性,help()
打印有关的信息type(printer)
,例如这memoized
类,它没有__doc__
属性。
这不被认为是一个错误,这都是设计使然;help()当您传入实例时将始终查看该类 https://hg.python.org/cpython/file/d4630b1c8792/Lib/pydoc.py#l1552。如果需要,不要使用类作为装饰器help()
用于装饰函数,或升级您的 Python 版本。
这最终是Python 3.9 中的更改 https://docs.python.org/3/whatsnew/3.9.html#pydoc,参见错误报告讨论 https://github.com/python/cpython/issues/84438.
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)