Python:什么意思?

2024-05-19 07:04:55 发布

您现在位置:Python中文网/ 问答频道 /正文

在Python中,使用*=意味着什么。例如:

for i in xrange(len(files)):
    itimes[i,:,:] *= thishdr["truitime"]

Tags: inforlenfilesxrangetruitimeitimesthishdr
3条回答

它的意思是“[左边的表达式]=[本身]*[右边的表达式]”:

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']                                                                                                                                                                                          

相关问题 更多 >

    热门问题