Possible Duplicate:
python: are property fields being cached automatically?
As a concern about effeciency of properties in python, I was wondering when and how often they are called.
To use a simple example, say I subclass namedtuple and I have something like:
from collections import namedtuple
from math import pi
class Circle (namedtuple('Circle', 'x, y, r')):
__slots__ = ()
@property
def area(self):
return pi*self.r**2
unitCircle = Circle(0, 0, 1.0)
print 'The area of the unit circle is {0} units'.format(unitCircle.area)
I assume that area is not calculated until the first time it is called, but once it is called, is that value cached until something changes or is it recalculated every time it is called?
Put another way, if I have a property that (unlike this one) is relatively expensive to calculate and will be used repeatedly, should I let it be a property, or is it more effecient to store it as a value and explicitly caclulate it when it really needs to be updated?
Properties are not cached unless you do it explicitly, so the code is run every time the property is accessed. Try:
If you want to be able to recalculate the value on demand occasionally, do something like:
Or, if you want to do it more automatically: