import weakref
class Cached(type):
def __init__(cls, *args, **kwargs):
super().__init__(*args, **kwargs)
# weakref 不影响GC
# 缓存中常用 weakref
cls._cache = weakref.WeakValueDictionary()
def __call__(cls, *args):
# tuple 作为 key
if args in cls._cache:
return cls._cache[args]
else:
# 此处对调用 Logger类中的 __new__ __init__ 方法
obj = super().__call__(*args)
cls._cache[args] = obj
return obj
class CachedBase(metaclass=Cached):
pass
class Logger(CachedBase):
# Logger() 首先会走到元类的 __call__ 方法
def __init__(self, name):
self.name = name
if __name__ == '__main__':
l1 = Logger('l1')
l2 = Logger('l2')
l3 = Logger('l1')
print(l1 is l2)
print(l1 is l3)
Python用元类实现缓存实例
于 2023-05-26 14:37:28 首次发布