I’m confused about the following code snippet how it works? It’s a decorator and it will lazily initialize the property and then use the cached property on next requests. Looking at the code, it seems that it will always call the self.method? A little explanation will be helpful
class cached_property(object):
def __init__(self, method, name=None):
self.method = method
self.name = name or method.__name__
self.__doc__ = method.__doc__
def __get__(self, inst, cls):
if inst is None:
return self
result = self.method(inst)
setattr(inst, self.name, result)
return result
To me, it looks like it calls the method the first time around
result = self.method(inst). It then replaces the method on the instance with the result:setattr(inst,self.name,result).On subsequent
my_instance.my_cached_property, you’re actually accessing the (initial) result of the method (as a regular attribute) as opposed to the descriptor (the original method and the descriptor class are no bound to the class since you overwrote that attribute).