I have a class that takes only one input argument. This value will then be used to compute a number of attributes (only one in the following example). What is a pythonic way if I wanted to take the computation place only if I call the attribute. In addition, the result should be cached and attr2
must not be set from outside the class.
JavaScript
x
15
15
1
class LazyInit:
2
def __init__(self, val):
3
self.attr1 = val
4
self.attr2 = self.compute_attr2()
5
6
def compute_attr2(self):
7
return self.attr1 * 2 # potentially costly computation
8
9
10
if __name__ == "__main__":
11
obj = LazyInit(10)
12
13
# actual computation should take place when calling the attribute
14
print(obj.attr2)
15
Advertisement
Answer
Make attr2
a property, not an instance attribute.
JavaScript
1
11
11
1
class LazyInit:
2
def __init__(self, val):
3
self.attr1 = val
4
self._attr2 = None
5
6
@property
7
def attr2(self):
8
if self._attr2 is None:
9
self._attr2 = self.compute_attr2()
10
return self._attr2
11
_attr2
is a private instance attribute that both indicates whether the value has been computed yet, and saves the computed value for future access.