后续:超类中的属性缓存

时间:2017-03-21 02:11:28

标签: python-3.x caching properties

这是this question的后续内容。我有一个类来缓存其子类的属性:

class A(object):

    def __init__(self):
        self._value = None

    @property
    def value(self):
        if self._value is None:
            self._value = self.complex_computation()
        return self._value

    def complex_computation(self):
        raise NotImplemented

现在,假设我有许多A的子类,每个子类只覆盖complex_computation(),因此将缓存机制委托给父类。现在让我们假设其中一个类BB本身有一个子类C

class B(A):
    def complex_computation(self):
        return # B's complex computation happens here

class C(B):
    def complex_computation(self):
        return # C's complex computation happens here

但是,我们假设C还希望返回B value仍然使用类{{1}中定义的缓存机制}。 A可以添加以下方法:

C

如上一个问题所述,这不起作用。实际上,如果首先访问def parent_complex_computation(self): return super().value # this does not work C,那么value将始终返回该版本。首先使用parent_complex_computation(),缓存parent_complex_computation()的值时,会出现同样的问题。

正如前一个问题中所回答的,名称修改(即在B中使用self.__value而不是self._value)可以解决问题,但在这种情况下,{{1}的每个子类应该将缓存机制重新定义为自己的属性和受损的属性。是否有更好的方法将缓存机制仅保留在类A中而不重复代码,同时允许子类覆盖缓存的方法A并调用父缓存的{{1}因此缓存这两个值?

1 个答案:

答案 0 :(得分:0)

您有几个选择:

  • 重新设计__init__以找出名称正确的名称版本的名称,以便它始终适合于它所在的类

  • 将缓存行为移至complex_computation()方法

我将展示第二种方法:

def complex_computation(self, _cache=[]):
    if not _cache:
        # calculate
        # ...
        # calculated_value = ...
        # 
        # and save
        _cache.append(calculated_value)

    return _cache[0]

然后当你想看到你的直接父母的价值时:

def get_parent_calculation(self):
    return super().complex_computation()