Search code examples
pythonclassgetter-setter

Calling a method in setter in python


I want to implement a class property that is computed from other properties.

class Sum(object):

    @property
    def a(self):
        return self._a

    @a.setter
    def a(self, val):
        self._a = a
        self._constructSeries()

    @property
    def b(self):
        return self._b

    @b.setter
    def b(self, val):
        self._b = b
        self._constructSeries()

    def _constructSeries(self):
        # Some calculations involving a and b
        self._series = function(a, b)

    def __init__(self, a, b):
        self.a = a
        self.b = b

One way I know of is to define series as a property

@property
def series(self):
    return fun(a,b)

But I want to avoid calling fun each and every time as it takes a lot of computations. What is the standard way to handle such a case?


Solution

  • If I got it right you want to be able to change a and b without computing the fun everytime but when you request the result of the fun is the most updated one, is it correct?

    In such a case you can use property

    def get_series(self):
        if self._series is None or self.updated is False:
            self._series = fun(self.a,self.b)
            self.updated = True
        return self._series
    series = property(get_series)
    

    And when you set a and b you update the flag

    @property
    def a(self):
        self.updated = False
        return self._a
    
    
    @property
    def b(self):
        self.updated = False
        return self._b
    

    Then self.series returns the updated values but it runs fun just if the input changes from the last time it has been computed.