Skip to content Skip to sidebar Skip to footer

Caching Attributes In Superclass

I have a class which caches some values to avoid computing them many times, for instance class A(object): def __init__(self, a, b): self.a = a self.b = b

Solution 1:

What you need to do is use name-mangling -- this will allow each class/subclass to maintain a private version of the variable so they don't clobber each other:

classA(object):

    def__init__(self, a, b):
        self.a = a
        self.b = b
        self.__value = None    @propertydefvalue(self):
        if self.__value isNone:
            self.__value = 7return self.__value

classB(A):

    def__init__(self, a, b):
        super().__init__(a, b)
        self.__value = None    @propertydefvalue(self):
        if self.__value isNone:
            self.__value = 17return self.__value

    defget_old_value(self):
        returnsuper().value  # no more trouble here

And in use:

>>>b = B(1, 2)>>>print(b.value)
17
>>>print(b.get_old_value())
7

Please note you now need to set __value in B's __init__ as well.

See also this answer for a couple more tidbits about name-mangling.

Post a Comment for "Caching Attributes In Superclass"