python缓存的属性:如何删除?

2024-04-23 09:06:35 发布

您现在位置:Python中文网/ 问答频道 /正文

考虑以下缓存和删除属性的类:

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()

删除此缓存属性是否正确?我不是舒尔那样做的


Tags: theinstancenameself属性initonfactory
1条回答
网友
1楼 · 发布于 2024-04-23 09:06:35

您的代码将尝试删除方法本身,而不是缓存的值。正确的方法是从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"]

相关问题 更多 >