python cached_property:如何删除?

lrn*_*rnv 7 python caching

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

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)

这是删除此缓存属性的正确方法吗?我不确定我的做法。

voo*_*ack 9

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

  • 我只是想提醒其他遇到这个问题/答案的人,如果您使用 **现有的 Python** 或 **Django** `cached_property` 装饰器,正确的答案是删除该属性(例如`删除 self.my_cached_attribute`)。我最初错过了这样一个事实,即这个问题有自己的自定义“cached_property”类,并且它是我的最佳 Google 结果。 (23认同)