Static variable vs Class variable

Paul Melis paul.melis at gmail.com
Wed Oct 17 14:57:50 CEST 2007


On Oct 17, 2:39 pm, Duncan Booth <duncan.bo... at invalid.invalid> wrote:
> Marc 'BlackJack' Rintsch <bj_... at gmx.net> wrote:
>
> > Simply not to introduce special cases I guess.  If you write ``x.a +=
> > b`` then `x.a` will be rebound whether an `a.__iadd__()` exists or
> > not. Otherwise one would get interesting subtle differences with
> > properties for example.  If `x.a` is a property that checks if the
> > value satisfies some constraints ``x.a += b`` would trigger the set
> > method only if there is no `__iadd__()` involved if there's no
> > rebinding.
>
> Unfortunately that doesn't work very well. If the validation rejects the
> new value the original is still modified:
>
> >>> class C(object):
>
>         def setx(self, value):
>                 if len(value)>2:
>                         raise ValueError
>                 self._x = value
>         def getx(self):
>                 return self._x
>         x = property(getx, setx)
>
> >>> o = C()
> >>> o.x = []
> >>> o.x += ['a']
> >>> o.x += ['b']
> >>> o.x += ['c']
>
> Traceback (most recent call last):
>   File "<pyshell#27>", line 1, in <module>
>     o.x += ['c']
>   File "<pyshell#22>", line 4, in setx
>     raise ValueError
> ValueError
>
> >>> o.x
> ['a', 'b', 'c']

Now that's really interesting. I added a print "before" and print
"after" statement just before and after the self._x = value and these
*do not get called* after the exception is raised when the third
element is added.




More information about the Python-list mailing list