@x.setter property implementation

Floris Bruynooghe floris.bruynooghe at gmail.com
Fri Apr 11 08:07:40 EDT 2008


Oh, that was a good hint!  See inline

On Apr 11, 12:02 pm, Arnaud Delobelle <arno... at googlemail.com> wrote:
> On Apr 11, 11:19 am, Floris Bruynooghe <floris.bruynoo... at gmail.com>
> wrote:
> [...]
>
> > > Unfortunatly both this one and the one I posted before work when I try
> > > them out on the commandline but both fail when I try to use them in a
> > > module.  And I just can't figure out why.
>
> > This in more detail: Imaging mod.py:
>
> > import sys
>
> > _property = property
>
> > class property(property):
> >     """Python 2.6/3.0 style property"""
> >     def setter(self, fset):
> >         cls_ns = sys._getframe(1).f_locals
> >         for k, v in cls_ns.iteritems():
> >             if v == self:
> >                 propname = k
> >                 break
> >         cls_ns[propname] = property(self.fget, fset,
> >                                     self.fdel, self.__doc__)
> >         return fset

return cls_ns[propname]

And then it works as I tried originally!

> > class Foo(object):
> >     @property
> >     def x(self):
> >         return self._x
>
> >     @x.setter
> >     def x(self, v):
>
>       ^^^^^
> Don't call this 'x', it will override the property, change it to
> 'setx' and everything will work.  The same probably goes for your own
> 'propset' decorator function.
>
> >         self._x = v + 1
>
> > Now enter the interpreter:
> > >> import mod
> > >>> f = mod.Foo()
> > >>> f.x = 4
> > >>> f.x
>
> > 4
>
> > I don't feel like giving up on this now, so close...
>
> --
> Arnaud




More information about the Python-list mailing list