使用类定义装饰器时,如何自动转移__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) __qualname__python中有什么,它有什么用?
为什么我需要使用它__name__?
我阅读了文档,但它们并没有帮助我清楚地了解它的用处。
我已阅读获取 Python 类的完全限定名称 (Python 3.3+)。
这个问题问的是“如何获得一个合格的名字”,它假定人们知道“合格的名字”的含义。显然,该问题的答案是使用__qualname__属性。
我的问题是什么 __qualname__,为什么我应该在__name__.
要获取我们可以使用的类名的字符串表示,obj.__class__.__name__是否可以重载这些方法,以便我可以返回我的字符串而不是实际的类名?