property problem
Bengt Richter
bokr at oz.net
Thu Jul 18 15:38:50 EDT 2002
On Thu, 18 Jul 2002 15:44:58 +0200, Peter Maas <peter.maas at mplusr.de> wrote:
>Hi,
>
>while experimenting with class properties using Python 2.2.1
>I encountered the following weird behaviour:
>
>This is my testclass:
>
>class proptest:
>
> def __init__(self):
> self.__data = 0
>
> def get_data(self):
> return self.__data
>
> def set_data(self, value):
> self.__data = value
>
> data = property(get_data, set_data)
>
> def meth(self):
> return self.__data
>
>This is my testcode:
>
> >>> x = proptest()
> >>> x.data=234
> >>> x.data
>234
> >>> x.meth()
>0
> >>> x.set_data(234)
> >>> x.meth()
>234
>
>Explanation:
>
>The "data" property works but a change using the property
>name doesn't show in meth(). If I use the access function set_data
>it works as expected. Is it my fault or Python's?
>
All will be ok if you make your proptest inherit from object
(thus making it a new style class).
see
http://www.python.org/2.2/descrintro.html#property
and scroll down a bit for an explanation of what you're seeing above, starting with
"Things to notice about property() (all advanced material except the first one):
Properties do not work for classic classes, but you don't get a clear error
when you try this. Your get method will be called, so it appears to work,
but upon attribute assignment, a classic class instance will simply
set the value in its __dict__ without calling the property's set method,
and after that, the property's get method won't be called either.
(You could override __setattr__ to fix this, but it would be prohibitively expensive.)
..."
There's also other interesting stuff to read about in descrintro.html ;-)
Regards,
Bengt Richter
More information about the Python-list
mailing list