I would like to know what is the python way of initializing a class member but only when accessing it, if accessed. I tried the code below and it is working but is there somethi
Consider the pip-installable Dickens package which is available for Python 3.5+. It has a descriptors
package which provides the relevant cachedproperty
and cachedclassproperty
decorators, the usage of which is shown in the example below. It seems to work as expected.
from descriptors import cachedproperty, classproperty, cachedclassproperty
class MyClass:
FOO = 'A'
def __init__(self):
self.bar = 'B'
@cachedproperty
def my_cached_instance_attr(self):
print('Initializing and caching attribute, once per class instance.')
return self.bar * 2
@cachedclassproperty
def my_cached_class_attr(cls):
print('Initializing and caching attribute, once per class.')
return cls.FOO * 3
@classproperty
def my_class_property(cls):
print('Calculating attribute without caching.')
return cls.FOO + 'C'