update attribute - (newbie)

Larry Bates larry.bates at websafe.com
Tue Dec 19 09:49:54 EST 2006


Bruce wrote:
>>>> class A:
> ...  def __init__(self):
> ...   self.t = 4
> ...   self.p = self._get_p()
> ...  def _get_p(self):
> ...   return self.t
> ...
>>>> a = A()
>>>> a.p
> 4
>>>> a.t += 7
>>>> a.p
> 4
> 
> I would like to have it that when I ask for p, method _get_p is always
> called so that attribute can be updated. How can I have this
> functionality here? thanks
> 
Something like this?

class A:
    def __init__(self):
        self.t=4
        return

    def __getattr__(self, name):
        if name == 'p': return self.t
        else: return self.__dict__[name]


if __name__ == "__main__":
    a=A()
    print a.p
    a.t+=7
    print a.p



More information about the Python-list mailing list