python 单实例运行

2019-12-12 16:26:45 浏览数 (1)

工厂函数

代码语言:javascript复制
class CachedSpamManager2:
 def init(self):
 self._cache = weakref.WeakValueDictionary()
代码语言:javascript复制
def get_spam(self, name):
    if name not in self._cache:
        temp = Spam3._new(name)  # Modified creation
        self._cache[name] = temp
    else:
        temp = self._cache[name]
    return temp

def clear(self):
        self._cache.clear()
代码语言:javascript复制
class Spam3:
 def init(self, *args, **kwargs):
 raise RuntimeError("Can't instantiate directly")
代码语言:javascript复制
# Alternate constructor
@classmethod
def _new(cls, name):
    self = cls.__new__(cls)
    self.name = name
    return self

或者

The class in question

代码语言:javascript复制
class Spam:
 def init(self, name):
 self.name = name

Caching support

代码语言:javascript复制
import weakref
 _spam_cache = weakref.WeakValueDictionary()
 def get_spam(name):
 if name not in _spam_cache:
 s = Spam(name)
 _spam_cache[name] = s
 else:
 s = _spam_cache[name]
 return s

0 人点赞