【发布时间】:2018-04-26 10:29:42
【问题描述】:
我想写一个装饰器,允许记忆构造函数。当我构造一个类时,我希望尽可能从缓存中返回对象。
以下代码改编自here。
from functools import wraps
def cachedClass(klass):
cache = {}
@wraps(klass, updated=())
class wrapper:
def __new__(cls, *args, **kwargs):
key = (cls,) + args + tuple(kwargs.items())
try:
inst = cache.get(key, None)
except TypeError:
# Can't cache this set of arguments
inst = key = None
if inst is None:
inst = klass.__new__(klass, *args, **kwargs)
inst.__init__(*args, **kwargs)
if key is not None:
cache[key] = inst
return inst
return wrapper
一个小型测试套件揭示了以下内容:
>>> @cachedClass
... class Foo:
... pass
>>> f1 = Foo()
>>> f2 = Foo()
>>> f1 is f2
True
>>> Foo
<class 'cache.Foo'>
>>> type(f1)
<class 'cache.Foo'>
>>> isinstance(f1, Foo)
False
我预计最后一个表达式会返回 True。我错过了什么?
【问题讨论】:
-
我使用的是 Python 2.7,我确实收到了
True。但是,当我运行type(f1)时,解释器也会返回<type 'instance'>。 -
@HFBrowning 因为
class Foo: pass是 Python 2 中的旧式类。
标签: python python-3.x constructor memoization