integers ( ++ operator ? )

Alex Martelli aleaxit at yahoo.com
Wed Jun 6 05:14:40 EDT 2001


"Nick Perkins" <nperkins7 at home.com> wrote in message
news:rZhT6.142247$eK2.34099848 at news4.rdc1.on.home.com...
>
> "Alan Daniels" <daniels at mindspring.com> wrote in message
>
> > I believe the new "x += 1" syntax is just synactic sugar which serves
> > as shorthand for "x = x + 1", although I'd have to delve through the
> > interpreter source code to be 100% sure.
>
> ..no need to look at the interpreter source:
>
> >>> x=10
> >>> id(x)
> 3161552
> >>> x+=1
> >>> id(x)
> 3161960
>
> x does indeed refer to a different object.

Ah, but that depends, you see...:

D:\ian\good>python
Python 2.1 (#15, Apr 16 2001, 18:25:49) [MSC 32 bit (Intel)] on win32
Type "copyright", "credits" or "license" for more information.
Alternative ReadLine 1.4 -- Copyright 2001, Chris Gonnerman
>>> class Int:
...   def __init__(self, i): self.i=i
...   def __iadd__(self, other): self.i+=other; return self
...   def __repr__(self): return 'Int('+str(self.i)+')'
...
>>> x=Int(10)
>>> x
Int(10)
>>> id(x)
8364268
>>> x+=1
>>> x
Int(11)
>>> id(x)
8364268
>>>

If x belongs to a mutable type defining a suitable __iadd__
(inplace-add), then its id() is NOT changed by +=... to be
more precise, x doesn't need to be re-bound then (it's
rebound to what __iadd__ returns, which is self, if you
prefer:-).  So, += is *NOT* just syntax sugar... it's an
important polymorphic way to "increment" objects that can
be either mutable or immutable, doing the best possible
thing in each case!-)


Alex






More information about the Python-list mailing list