I am working with objects, which have many attributes. I am not using all of the attributes but if I access one then I will use it many times. Is it possible to initialize an attribute only during the first time it gets accessed. I came up with the following code, which is sadly really slow.
class Circle():
def __init__(self,radius):
self.radius = radius
self._area = None
@property
def area(self):
if self._area is None:
self._area = self.radius**2 * np.pi
return self._area
Is there an efficient way to achieve this?
For Python 3.8 or greater, use the @cached_property decorator. The value is calculated on first access.
from functools import cached_property
class Circle():
def __init__(self,radius):
self.radius = radius
self._area = None
@cached_property
def area(self):
if self._area is None:
self._area = self.radius**2 * np.pi
return self._area
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With