天天看点

python使用元类和weakref创建缓存实例

一:缓存实例的意义?

缓存实例,简言之,使用相同参数时只创建一个实例,避免内存浪费等,如:

import logging

aa = logging.getLogger('foor')
bb = logging.getLogger('foor')
print(aa == bb)
# True,aa和bb其实是同一个实例
           

二:使用元类和wearkref实现缓存实力。

import weakref

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

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

class Spam(metaclass=Cached):

    def __init__(self, name):
        print('Creating Spam {}'.format(name))
        self.name = name
a = Spam('HELLO')
b = Spam('HELLO')
print(a == b)