考虑以下从类中缓存和删除属性的系统:
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()
Run Code Online (Sandbox Code Playgroud)
这是删除此缓存属性的正确方法吗?我不确定我的做法。
您的代码将尝试删除方法本身,而不是缓存的值。正确的方法是从self.__dict__(数据实际存储的位置)删除密钥。
这是我目前正在做的事情中的一个例子:
def Transform:
...
@cached_property
def matrix(self):
mat = Matrix44.identity()
mat *= Matrix44.from_translation(self._translation)
mat *= self._orientation
mat *= Matrix44.from_scale(self._scale)
return mat
@property
def translation(self):
return self._translation
@translation.setter
def translation(self, value: Vector3):
self._translation = value
if "matrix" in self.__dict__:
del self.__dict__["matrix"]
Run Code Online (Sandbox Code Playgroud)