使用类定义装饰器时,如何自动转移__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 …Run Code Online (Sandbox Code Playgroud)