首页
学习
活动
专区
圈层
工具
发布

python 缓存模式

import weakref

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

代码语言:javascript
复制
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

下一篇
举报
领券