+= return value
Michael Hudson
mwh21 at cam.ac.uk
Tue Jan 23 15:37:16 EST 2001
shochet at hotmail.com writes:
> I am confused with the return values of the augmented assignment
> opertators. When redefining them in a class, what should they return?
self, probably.
Try this link:
http://python.sourceforge.net/devel-docs/ref/numeric-types.html#l2h-214
> Coming from a C++ background, I assumed returning None (aka void) would
> suffice, but it looks like you need to return self (?)
You have methods of the form
void operator+=(blah);
in C++? That's, err, wrong. (It's not how int's behave, for
example).
> 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.
Where do these wrappers come from? Change them, or slap their author
into doing so.
> 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.
No, because executing
f += g
rebinds f, as all assignment does in Python.
> Even stranger is:
> x = 2
> x += 1
> ...does not return anything but it works!?
Hmm. What you return from the __iadd__ method is *not* the "result"
of the "expression"
f += g
because that is not an expression but rather a statement and
statements have no result (hence the quotation marks above).
To a certain degree of approximation
f += g
behaves as if it was written
f = f.__iadd__(g)
I hope this helps - certainly answering it has helped *me* understand
things better, even if it doesn't help you when you read it...
Cheers,
M.
--
I love the way Microsoft follows standards. In much the same manner
that fish follow migrating caribou. -- Paul Tomblin
-- http://home.xnet.com/~raven/Sysadmin/ASR.Quotes.html
More information about the Python-list
mailing list