Recently I've been writing a bunch of code like this:
class A:
def __init__(self, x):
self.x = x
self._y = None
def y(self):
if self._y is None:
self._y = big_scary_function(self.x)
return self._y
def z(self, i):
return nice_easy_function(self.y(), i)
In a given class I may have a number of things working like this y
, and I may have other things that use the stored pre-calculated values. Is this the best way to do things or would you recommend something different?
Note that I don't pre-calculate here because you might use an instance of A
without making use of y
.
I've written the sample code in Python, but I'd be interested in answers specific to other languages if relevant. Conversely I'd like to hear from Pythonistas about whether they feel this code is Pythonic or not.
See Question&Answers more detail:os