tough-to-explain Python

Gabriel Genellina gagsl-py2 at yahoo.com.ar
Wed Jul 8 10:13:42 CEST 2009


En Wed, 08 Jul 2009 04:32:07 -0300, Francesco Bochicchio  
<bieffe62 at gmail.com> escribió:

> I would go with something like this:
>
> """
> In object oriented programming, the same function or operator can be
> used to represent
> different things. This is called overloading. To understand what the
> operator/function do, we have to look at
> the kind of object it is applied to.
> In this case, the operator "+=" means two different things:
> - for strings and numbers it means : "create a new object by merging
> the two operands". This is why the original object is left the same.
> - for lists, it means : "increase the left operand with the contents
> of the right operand". This is why the original object is changed
> """

Mmm, but this isn't quite exact. += isn't an operator, but a statement  
(augmented assignment). a += b translates to: [*]

a = a.__iadd__(b) [*]

It's up to the __iadd__ implementation to return the same object or a new  
one, and the assignment occurs even if the same object is returned.

If you think of an assignments as binding names to objects (well, that's  
the documented behavior, btw) things become more clear.

> P:S : Sometime I think they should not have allowed += on immutables
> and forced everybody to write s = s + "some more".

I think not everyone agreed when += was introduced.
But now, having s += "some more" allows the operation to be optimized.

[*] except 'a' is evaluated only once

-- 
Gabriel Genellina




More information about the Python-list mailing list