The @cached_property()
decorator provides a convenient way to cache the results of methods.
When a method is decorated using this decorator, it only gets called once and the returned value is assigned to a variable with same name as the method. The value can then be accessed using the variable rather than recomputing it each time.
The decorator is particularly useful for expensive operations which are unlikely to change after the first time they are computed.
class MyClass:
@cached_property
def my_func(self):
#statements
from functools import cached_property
class Person:
def __init__(self, name, country):
self.name = name
self.country = country
@cached_property
def get_info(self):
return f"{self.name} from {self.country}"
p = Person('Rahul', 'India')
#access the method result as an attribute
print(p.get_info)
#the value does not change even after updating relevant attribute
p.name = 'Jane'
p.country = 'Canada'
print(p.get_info)
As you can see above we access the method results as a mere attribute.