# The class in questionclassSpam:def__init__(self,name):self.name = name# Caching supportimport weakref_spam_cache = weakref.WeakValueDictionary()defget_spam(name):if name notin _spam_cache: s =Spam(name) _spam_cache[name]= selse: s = _spam_cache[name]return s
>>> a = get_spam('foo')
>>> b = get_spam('bar')
>>> a is b
False
>>> c = get_spam('foo')
>>> a is c
True
import weakref
class CachedSpamManager:
def __init__(self):
self._cache = weakref.WeakValueDictionary()
def get_spam(self, name):
if name not in self._cache:
s = Spam(name)
self._cache[name] = s
else:
s = self._cache[name]
return s
def clear(self):
self._cache.clear()
class Spam:
manager = CachedSpamManager()
def __init__(self, name):
self.name = name
def get_spam(name):
return Spam.manager.get_spam(name)
>>> a = Spam('foo')
>>> b = Spam('foo')
>>> a is b
False