在Python中,*=
是什么意思。例如:
for i in xrange(len(files)):
itimes[i,:,:] *= thishdr["truitime"]
最佳答案
正如其他人所解释的,这大致相当于:
[object] = [object] * [another_object]
然而,这并不完全相同。从技术上讲,上面调用了 __mul__
函数,该函数返回一个值,并将其重新分配回名称。
例如,我们有一个对象 A
并将它与 B
相乘。过程大概是这样的:
> Call the __mul__ function of object A,
> Retrieve the new object returned.
> Reassign it to the name A.
看起来很简单。现在,通过执行 *=
,我们不会调用方法 __mul__
,而是调用 __imul__
,它将尝试修改自身。过程大概是这样的:
> 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.
有了这个,您就地修改它,而不是创建一个新对象。
那又怎样?看起来一样..
不完全是。如果您替换了一个对象,您就在内存中为它创建了一个新位置。如果就地修改,内存中的对象位置将始终相同。
看看这个控制台 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]
如果我们检查内存地址:
>>> id(a) == id(b)
错误
使用它,b
的值没有改变,因为 a
现在只是指向一个不同的地方。但是使用 *=
:
>>> 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]
如果我们检查内存地址:
>>> id(a) == id(b)
True
该操作也会影响 b
。这可能很棘手,有时会导致困惑的行为。但是一旦你理解了它,它就会很容易处理。
希望这对您有所帮助!
关于Python:*= 是什么意思?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20622890/