Skip to content Skip to sidebar Skip to footer

Followup: Attribute Caching In Superclasses

This is a followup to this question. I have a class which caches an attribute for its subclasses: class A(object): def __init__(self): self._value = None @propert

Solution 1:

You have a couple options:

  • redesign __init__ to figure out the correct name-mangled version of the name so it is always appropriate for the class it is in

  • move the caching behavior into the complex_computation() method

I'll show the second method:

defcomplex_computation(self, _cache=[]):
    ifnot_cache:# calculate# ...# calculated_value = ...# # and save
        _cache.append(calculated_value)

    return _cache[0]

And then when you want to see your immediate parent's value:

defget_parent_calculation(self):
    returnsuper().complex_computation()

Post a Comment for "Followup: Attribute Caching In Superclasses"