gpt4 book ai didi

python cached_property : how to delete?

转载 作者:行者123 更新时间:2023-12-04 12:37:28 28 4
gpt4 key购买 nike

考虑以下从类中缓存和删除属性的系统:

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__ 中删除 key 。 (这是实际存储数据的地方)。
这是我目前正在研究的一个例子:

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"]

关于python cached_property : how to delete?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59899732/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com