Python functools.wraps等效于类
|
当使用类定义装饰器时,如何自动传递
__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方法(我假设这是用于创建绑定方法?)是否缺少任何方法?
没有找到相关结果
已邀请:
5 个回复
蹄渭信妥扳
勘掸府迫路
用法:
输出:
编辑: 如果您想知道为什么未包含在stdlib中是因为您可以 将您的类装饰器包装在函数装饰器中,并使用
像这样:
联海
公藕
这就是您所需要的。一般来说。它不会保留签名,但是如果您确实希望可以使用库来执行此操作。我还继续重写了记忆代码,以便它也适用于关键字参数。还有一个错误,即无法将其转换为可哈希的元组将导致它无法在100%的情况下运行。 用
修改其行为的重写
装饰器演示。
现在是一个包装原始类的函数,尽管您可以(像其他答案一样)编写一个包装类,或者甚至更好地,它可以检测出它是否是一个类,并且是否包装了s15ѭ方法。
实际上:
攫怂绵十
并且,用法: