생성자를 메모 할 수있는 데코레이터를 작성하고 싶습니다. 클래스를 생성 할 때 가능하면 객체가 캐시에서 반환되기를 바랍니다.왜이 경우 isinstance()가 False를 반환합니까?
다음 코드는 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
작은 테스트 스위트는 다음과 revals :
>>> @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
를 반환 할 것으로 예상. 내가 뭘 놓치고 있니?
저는 파이썬 2.7을 사용하고 있습니다. 'True'를 얻습니다. 그러나 인터프리터는'type (f1)'을 실행할 때''를 반환합니다. –
HFBrowning
@HFBrowning 왜냐하면'class Foo : pass'는 파이썬 2의 구식 클래스이기 때문입니다. – vaultah