python call set property when property missing -
i have object has several properties containing values take while query. dont want values properties when create instance, when code path requires property few needed depending on code path. order when reach points int eh code not deterministic, cant set property @ fixed point in script. going create method
def getvalue(self, attributename): if hasattr(self, attributename): return getattr(self, attributename) elif attributename == 'a1': v = ... code value a1 self.a1 = v return v elif attributename == 'a2': v = ... code value a2 self.a2 = v return v ....
but wondering if way deal or if there smarter ways preferred. comment
you can use decorator:
class cached_property(object): """define property caching value on per instance basis. decorator converts method single self argument property cached on instance. """ def __init__(self, method): self.method = method def __get__(self, instance, type): res = instance.__dict__[self.method.__name__] = self.method(instance) return res
here explanation.
Comments
Post a Comment