__iadd__ useless in sub-classed int
Diez B. Roggisch
deets at nospam.web.de
Thu Dec 6 14:12:58 EST 2007
samwyse schrieb:
> For whatever reason, I need an inproved integer. Sounds easy, let's
> just subclass int:
>
>>>> class test(int):
> pass
>
> Now let's test it:
>
>>>> zed=test(0)
>>>> zed.__class__
> <class '__main__.test'>
>>>> zed
> 0
>
> So far, so good. Now let's try incrementing:
>
>>>> zed+=1
>>>> zed
> 1
>>>> zed.__class__
> <type 'int'>
>
> WTF??!
> Is this a bug or is it the inevitable result of optimizing for the
> case where all integers are indistinguishable?
There has been a lengthe thread over the semantics of __iadd__ a few
weeks ago. It _can_ modify the object in question in-place (something
not possible for ints anyway), but it will ALWAYS return a reference
which will be set to the left-hand-side.
zed = zed.__iadd__(1)
So - you need to overload the __iadd__-method to return a test-instance.
Diez
More information about the Python-list
mailing list