当使用一个类中定义一个装饰,我怎么自动转移__name__,__module__和__doc__?通常,我会使用functools中的@wraps装饰器。这是我为一个类所做的事情(这不完全是我的代码):
class memoized:
"""Decorator that caches a function's return value each time it is called.
If called later with the same arguments, the cached value is returned, and
not re-evaluated.
"""
def __init__(self, func):
super().__init__()
self.func = func
self.cache = {}
def __call__(self, *args):
try:
return self.cache[args]
except KeyError:
value = self.func(*args)
self.cache[args] = value
return value
except TypeError:
# uncacheable -- for instance, passing a list as an argument.
# Better to not cache than to blow up entirely.
return self.func(*args)
def __repr__(self):
return self.func.__repr__()
def __get__(self, obj, objtype):
return functools.partial(self.__call__, obj)
__doc__ = property(lambda self:self.func.__doc__)
__module__ = property(lambda self:self.func.__module__)
__name__ = property(lambda self:self.func.__name__)
是否有一个标准的装饰器来自动创建名称模块和文档?另外,要使get方法自动化(我想这是为了创建绑定方法?)是否缺少任何方法?
__name__和__doc__设置在实例,而不是类,这是始终使用help(instance)。要修复,不能使用基于类的装饰器实现,而必须将装饰器实现为一个函数。有关详细信息,请参见stackoverflow.com/a/25973438/1988505。