
En Thu, 30 Apr 2009 17:59:55 -0300, Jared Grubb escribió:
It is not possible if one insist on using property. But Oleg Broytmann's CachedAttribute class works fine -- it seems to me it didn't get the deserved attention. I'll repost a slightly modified version: class CachedAttribute(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 class Foo(object): @CachedAttribute def expensive(self): "docstring for the expensive property" print("computing value...") return 42 py> f = Foo() py> f.expensive computing value... 42 py> f.expensive 42 py> f.expensive = 43 py> f.expensive 43 py> del f.expensive py> f.expensive computing value... 42 py> f.expensive 42 py> Note that once the value is computed, it becomes an instance attribute; later accesses retrieve it directly, no indirection is involved. -- Gabriel Genellina Yahoo! Cocina Recetas prácticas y comida saludable http://ar.mujer.yahoo.com/cocina/
participants (1)
-
gagsl-py2@yahoo.com.ar