Static variable vs Class variable
Paul Melis
paul.melis at gmail.com
Wed Oct 17 09:45:17 EDT 2007
On Oct 17, 3:41 pm, Paul Melis <paul.me... at gmail.com> wrote:
> On Oct 17, 3:20 pm, Marc 'BlackJack' Rintsch <bj_... at gmx.net> wrote:
>
>
>
> > On Wed, 17 Oct 2007 05:57:50 -0700, Paul Melis wrote:
> > > On Oct 17, 2:39 pm, Duncan Booth <duncan.bo... at invalid.invalid> wrote:
> > >> >>> 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.
>
> > Well, of course not. Did you really expect that!? Why?
>
> Because o.x *is* updated, i.e. the net result of self._x = value is
> executed.
Argh, the getter is of course used to append the third element, after
which the rebinding triggers the exception. Got it now...
Paul
More information about the Python-list
mailing list