update attribute - (newbie)

Diez B. Roggisch deets at nospam.web.de
Tue Dec 19 09:47:06 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

You need to use a property, there are several possibilities to do so, a
common idiom is this:


class A(object):  # must be newstyle

   def __init__(self):
       self._p = 6


   def get_p(self):
       return self._p


   def set_p(self, v):
       self._p = v


   p = property(get_p, set_p)


Diez



More information about the Python-list mailing list