+= return value

Fredrik Lundh fredrik at effbot.org
Tue Jan 23 15:36:24 EST 2001


"shochet at hotmail.com>" wrote:
> I am confused with the return values of the augmented assignment
> opertators. When redefining them in a class, what should they return?
> Coming from a C++ background, I assumed returning None (aka void) would
> suffice, but it looks like you need to return self (?)
>
> class MyInt:
>     def __init__(self,value):
>         self.value = value
>     def __iadd__(self, other):
>         self.value = self.value + other.value
>         return None
>
> f = MyInt(1)
> g = MyInt(2)
> f+=g
>
> f is now None, not a MyInt with a value of 3 as I expected.
>
> So that is fine, returning self in __iadd__ does the trick, but now all
> the C++ code I have wrappers for that return void do not work. Does
> this appear broken to anybody else? Why do these operators need any
> return value? It would seem enough simply to set the object's internal
> state.

It's up to the object to determine if += should modify the lvalue,
or create a new object (not all objects can be modified in place).

For a little more info, see:

    http://python.sourceforge.net/peps/pep-0203.html

Hope this helps!

Cheers /F





More information about the Python-list mailing list