Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can you initialize an objects attribute the first time it gets accessed?

Tags:

python

oop

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?

like image 709
user509065 Avatar asked Nov 24 '25 11:11

user509065


1 Answers

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
like image 81
ac24 Avatar answered Nov 25 '25 23:11

ac24