A newbie question about class

Quinn Dunkan quinn at hork.ugcs.caltech.edu
Sat Feb 9 21:14:28 EST 2002

On 9 Feb 2002 16:35:19 -0800, newgene <newgene at bigfoot.com> wrote:
>can not get the value of "a.y" like the former. Of course I can use a
>method to set the value of "a.y", but is there a machanism to get the
>"a.y" automatically whenever I change the value of "a.x"?

Yes.  Under python2.2, it's (relatively) easy:

>>> class A:
...     def __init__(self, x=42):
...         self.x = x
...     def get_y(self):
...         return self.x**2
...     y = property(get_y, doc="'y' is computed as 'x**2'")
>>> a = A()
>>> a.y
>>> a.x = 2
>>> a.y

Under older pythons, it's a bit more tricky.  I'd recommend defining a
'get_y()' as above, and calling that instead of doing 'a.y'.  If you really
want 'a.y', then check the refman under 'customizing objects' or something for

More information about the Python-list mailing list