[英]Python: What does *= mean?
在Python中,當使用*=
時它意味着什么。 例如:
for i in xrange(len(files)):
itimes[i,:,:] *= thishdr["truitime"]
它只是意味着“[表達在左邊] = [本身] * [表達在右邊]”:
itimes[i,:,:] *= thishdr["truitime"]
相當於
itimes[i,:,:] = 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.
有了這個,你就可以就地修改它,而不是創建一個新對象。
所以呢? 它看起來一樣..
不完全是。 如果替換了對象,則會在內存中為其創建一個新位置。 如果您就地修改它,內存中的對象位置將始終相同。
看一下這個控制台會話:
>>> 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
。 這可能很棘手,有時會導致令人困惑的行為。 但是一旦理解了它,就很容易處理。
希望這可以幫助!
這意味着“將此變量設置為自身時間”
>>> fred = 10
>>> fred *= 10
>>> fred
100
>>> barney = ["a"]
>>> barney *= 10
>>> barney
['a', 'a', 'a', 'a', 'a', 'a', 'a', 'a', 'a', 'a']
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.