from functools import wraps
import timeclass CacheManager:def __init__(self):self._cache = {}def get_cache_obj(self, key):"""获取缓存对象"""return self._cache.get(key)def add_cache_obj(self, key, obj):"""添加缓存对象"""self._cache[key] = objreturn objdef __del__(self):"""清除所有缓存对象"""# print(f"CacheManager del")for k, v in self._cache.items():# print(f"CacheManager del:{k=}")del vself._cache.clear()del self._cache@classmethoddef cache_result(cls, func):"""装饰器:缓存结果,支持参数作为缓存的唯一键。"""@wraps(func)def wrapper(instance, *args, **kwargs):# 根据函数名和参数构建唯一缓存键key = f"{func.__name__}:{args}:{kwargs}"print(key)# 检查是否已缓存cache_obj = instance.cache_manager.get_cache_obj(key)if cache_obj is not None:print(cache_obj)return cache_obj# 缓存中没有对象,执行函数并缓存结果result = func(instance, *args, **kwargs)instance.cache_manager.add_cache_obj(key, result)print(result)return resultreturn wrapperclass MyClass:def __init__(self):self.cache_manager = CacheManager()def __del__(self):print("MyClass.__del__")@property@CacheManager.cache_resultdef oms_user(self):# 该代码只在缓存不存在时执行# return [1, 2, 3]return time.time()def test_cache():m = MyClass()print(id(m.oms_user))print(id(m.oms_user))test_cache()
结果
oms_user:():{}
1732000987.240014
2584475181488
oms_user:():{}
1732000987.240014
2584475181488
MyClass.__del__
Python cache 内存泄漏问题
创建于2411191534,修改于2411191534