In Python, what does it mean when *=
is used. For example:
for i in xrange(len(files)):
itimes[i,:,:] *= thishdr["truitime"]
As others have explained, this is roughly an equivalent to:
[object] = [object] * [another_object]
However, it's not exactly the same. Technically, the above calls the __mul__
function, which returns a value, and reassign it back to the name.
For example, we have an object A
and multiplying it with B
. The process is something like this:
> Call the __mul__ function of object A,
> Retrieve the new object returned.
> Reassign it to the name A.
Looks simple. Now, by doing *=
we're not invoking the method __mul__
, but instead __imul__
, which will attempt to modify itself. The process is something like this:
> Call the __imul__ function of object A,
> __imul__ will change the value of the object, it returns the modified object itself
> The value is reassigned back to the name A, but still points to the same place in memory.
With this, you're modifying it in-place, not creating a new object.
So what? It looks the same..
Not exactly. If you replaces an object, you created a new place for it in memory. If you modify it in-place, the object location in the memory will always be the same.
Take a look at this console session:
>>> a = [1, 2, 3]
>>> b = a
>>> c = 10
>>> a = a * c
>>> print a
[1, 2, 3, 1, 2, 3, 1, 2, 3, 1, 2, 3, 1, 2, 3, 1, 2, 3, 1, 2, 3, 1, 2, 3, 1, 2, 3, 1, 2, 3]
>>> b
[1, 2, 3]
If we check the memory address:
>>> id(a) == id(b)
False
Using this, the value of b
is unchanged, since a
is now just pointing to a different place. But using *=
:
>>> a = [1, 2, 3]
>>> b = a
>>> c = 10
>>> a *= c
>>> b
[1, 2, 3, 1, 2, 3, 1, 2, 3, 1, 2, 3, 1, 2, 3, 1, 2, 3, 1, 2, 3, 1, 2, 3, 1, 2, 3, 1, 2, 3]
And if we check the memory address:
>>> id(a) == id(b)
True
The operation affects b
as well. This can be tricky and leading to confusing behaviours, sometimes. But once you understand it, it would be easy to handle.
Hope this helps!
__imul__
does return its result (which is usually self
), and that result is assigned back to the variable.
It just means "[expression on the left] = [itself] * [expression on the right]":
itimes[i,:,:] *= thishdr["truitime"]
is equivalent to
itimes[i,:,:] = itimes[i,:,:] * thishdr["truitime"]
__imul__
method of the left hand side, which could do anything.
+=
, -=
, /=
, //=
&=
, |=
, <<=
, **=
, >>=
, and ^=
should all do what you expect them to, assuming you have reasonable definitions of __imul__
, __iadd__
, etc.
Dec 16, 2013 at 23:34
It means "set this variable to itself times "
>>> fred = 10
>>> fred *= 10
>>> fred
100
>>> barney = ["a"]
>>> barney *= 10
>>> barney
['a', 'a', 'a', 'a', 'a', 'a', 'a', 'a', 'a', 'a']