Static variable vs Class variable

Duncan Booth duncan.booth at invalid.invalid
Wed Oct 17 08:39:50 EDT 2007


Marc 'BlackJack' Rintsch <bj_666 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']
>>> 



More information about the Python-list mailing list