创建类的缓存实例

在创建一个类的对象时,如果之前使用同样参数创建过这个对象, 这时候不想在创建,而使用之前的实例缓存。
你希望相同参数创建的对象是单例的。可以使用 logging 模块,使用相同的名称创建的 logger 实例永远只有一个。
例1:

import logging
one = logging.getLogger('foo')
two = logging.getLogger('bar')
one is two
three = logging.getLogger('foo')
one is three

例2:

class Spam(object):
    def __init__(self, name):
        self.name = name


# Caching support
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


one = get_spam('foo')
two = get_spam('bar')
print(one is two)
three = get_spam('foo')
print(one is three)

高级用法

import weakref


class CachedSpamManager(object):
    def __init__(self):
        self._cache = weakref.WeakValueDictionary()

    def get_spam(self, name):
        if name not in self._cache:
            temp = Spam._new(name)  # Modified creation
            self._cache[name] = temp
        else:
            temp = self._cache[name]
        return temp

    def clear(self):
            self._cache.clear()

class Spam(object):
    def __init__(self, *args, **kwargs):
        raise RuntimeError("Can't instantiate directly")

    # Alternate constructor
    @classmethod
    def _new(cls, name):
        self = cls.__new__(cls)
        self.name = name
        return self

你可能感兴趣的:(Python-Classes)