@x.setter property implementation

Arnaud Delobelle arnodel at googlemail.com
Fri Apr 11 13:02:22 CEST 2008


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
>
> 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