在对另一个问题的答案的评论中,有人说他们不确定functools.wraps在做什么.所以,我问这个问题,以便在StackOverflow上有一个记录,供将来参考:究竟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 …Run Code Online (Sandbox Code Playgroud) deepcopy从copy不会复制一个类:
>>> class A(object):
>>> ARG = 1
>>> B = deepcopy(A)
>>> A().ARG
>>> 1
>>> B().ARG
>>> 1
>>> A.ARG = 2
>>> B().ARG
>>> 2
Run Code Online (Sandbox Code Playgroud)
这是唯一的方式吗?
B(A):
pass
Run Code Online (Sandbox Code Playgroud)