Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/281.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
python缓存的属性:如何删除?_Python_Caching - Fatal编程技术网

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

python缓存的属性:如何删除?,python,caching,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 b

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

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()
类缓存的\u属性(对象):
"""
用于在首次使用时按需构建属性的描述符(非数据)。
"""
def ___;初始(自身,工厂):
"""
被称为这样的:工厂(实例)来构建属性。
"""
self.\u attr\u name=工厂名称__
self.\u工厂=工厂
定义获取(自身、实例、所有者):
#构建属性。
attr=self.\u工厂(实例)
#缓存值;藏起来。
setattr(实例,self.\u attr\u name,attr)
返回属性
类测试():
定义初始化(自):
self.kikou=10
@缓存的不动产
def缓存(自):
打印(“计算一次!”)
返回真值
def清除缓存(自):
try:del self.caching
除了:通过
b=测试()
打印(b.缓存)
b、 清除缓存()

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

您的代码将尝试删除方法本身,而不是缓存值。正确的方法是从
self.\uuuu dict\uuuu
(实际存储数据的位置)中删除密钥

下面是我目前正在研究的一个例子:

def变换:
...
@缓存的不动产
def矩阵(自):
mat=Matrix44.identity()
mat*=Matrix44.自译(自译)
mat*=自定向
mat*=矩阵X44.自刻度(自刻度)
回程垫
@财产
def翻译(自我):
返回自我
@翻译设置器
def转换(自身,值:Vector3):
自我翻译=价值
如果“矩阵”在self.\u dict\u中:
del self._dict___[“矩阵”]

我只想提醒其他遇到这个问题/答案的人,如果您使用的是现有的Python或Django
cached\u属性
装饰器,正确的答案是删除该属性(例如
del self.my\u cached\u属性
)。起初,我忽略了这个问题有自己的自定义
cached_属性
类这一事实,它是我在谷歌搜索的最佳结果。