考虑以下缓存和删除属性的类:
class cached_property(object):
"""
Descriptor (non-data) for building an attribute on-demand on first use.
"""
def __init__(self, factory):
"""
<factory> is called such: factory(instance) to build the attribute.
"""
self._attr_name = factory.__name__
self._factory = factory
def __get__(self, instance, owner):
# Build the attribute.
attr = self._factory(instance)
# Cache the value; hide ourselves.
setattr(instance, self._attr_name, attr)
return attr
class test():
def __init__(self):
self.kikou = 10
@cached_property
def caching(self):
print("computed once!")
return True
def clear_cache(self):
try: del self.caching
except: pass
b = test()
print(b.caching)
b.clear_cache()
删除此缓存属性是否正确?我不是舒尔那样做的
您的代码将尝试删除方法本身,而不是缓存的值。正确的方法是从
self.__dict__
(实际存储数据的地方)删除密钥下面是我目前正在研究的一个例子:
相关问题 更多 >
编程相关推荐