Properties on old-style classes actually work?

Nick Vatamaniuc vatamane at gmail.com
Mon May 7 05:23:35 EDT 2007


On May 7, 4:44 am, Paul Melis <p... at science.uva.nl> wrote:
> Hello,
>
> The python library docs read in section 2.1
> (http://docs.python.org/lib/built-in-funcs.html):
>
> "
> ...
>
> property(       [fget[, fset[, fdel[, doc]]]])
>      Return a property attribute for new-style classes (classes that
> derive from object).
>
> ...
> "
>
> But in 2.4 at least properties also seem to work for old-style classes:
>
> class O:
>
>      def __init__(self):
>          self._x = 15
>
>      def get_x(self):
>          return self._x
>
>      x = property(get_x)
>
> o = O()
> print o.x
>
> outputs "15" as expected for the property.
>
> Regards,
> Paul

Paul,

Sorry to dissapoint, but properties don't work in old style classes.
The 'get' property seems to work but as soon as you use the set
property it fails and even 'get' won't work after that. It surely is
deceiving, I wish it would just give an error or something.  See
below.

-Nick Vatamaniuc




>>> class O:
   ....:     def __init__(self):
   ....:         self._x=15
   ....:     def get_x(self):
   ....:         print "in O.get_x()"
   ....:         return self._x
   ....:     def set_x(self,newx):
   ....:         print "in O.set_x(newx)"
   ....:         self._x=newx
   ....:     x=property(get_x, set_x)
   ....:

>>> o=O()

>>> o._x
15

>>> o.x
in O.get_x()
in O.get_x()
15

>>> o.x=42

>>> #DANGER WILL ROBINSON, set_x NOT CALLED!!!

>>> o.x
42

>>> #HMM... properties ARE BROKEN FROM NOW ON

>>> o._x
15

>>> #...BROKEN INDEED

>>>




More information about the Python-list mailing list