0

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?

1 Answer 1

2

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.

Sign up to request clarification or add additional context in comments.

2 Comments

You got my question right. Can you please explain the working of the function property a bit more?
I have just added the behaviour of self.series at the bottom of the answer, does it clarify enough? Basically using property() series becomes a "lazy" attribute that gets computed only when requested and in the case the input did not change it returns directly the previous value.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.