美文网首页
python 缓存模式

python 缓存模式

作者: SkTj | 来源:发表于2019-12-04 11:06 被阅读0次

    import weakref

    class Cached(type):
    def init(self, *args, *kwargs):
    super().init(
    args, **kwargs)
    self.__cache = weakref.WeakValueDictionary()

    def __call__(self, *args):
        if args in self.__cache:
            return self.__cache[args]
        else:
            obj = super().__call__(*args)
            self.__cache[args] = obj
            return obj
    

    Example

    class Spam(metaclass=Cached):
    def init(self, name):
    print('Creating Spam({!r})'.format(name))
    self.name = name

    调用

    a = Spam('Guido')
    Creating Spam('Guido')
    b = Spam('Diana')
    Creating Spam('Diana')
    c = Spam('Guido') # Cached
    a is b
    False
    a is c # Cached value returned
    True

    相关文章

      网友评论

          本文标题:python 缓存模式

          本文链接:https://www.haomeiwen.com/subject/agjbvctx.html