问题描述
我遇到了一些有趣的关于蟒蛇增量赋值 + =
i ran into something interesting about the python augmented assignment +=
这似乎是自动数据类型转换并不总是做 A + = B
如果是一个'简单'的数据类型,而 A = A + b
似乎总是工作
it seems to be automatic data type conversion is not always done for a += b
if a is a 'simpler' data type, while a = a + b
seems to work always
在这里转换完成情况
a = 1
b = 1j
a = 1
b = 0.5
情况下转换尚未完成。
case where the conversion is not done
from numpy import array
a = array([0, 0 ,0])
b = array([0, 0, 1j])
在 A + = B
, A
仍然是整数矩阵,而不是复杂的矩阵
after a += b
, a
remains as integer matrix, instead of complex matrix
我曾经以为 A + = B
相同 A = A + B
,请问是什么在底层实现他们的区别呢?
i used to think a += b
is the same as a = a + b
, what is the difference of them in the underlying implementation?
推荐答案
对于 +
运营商,Python中定义了一个对象可以实现三个特殊的方法:
For the +
operator, Python defines three "special" methods that an object may implement:
-
__ __添加
:增加了两个项目(+
运营商)。当你做A + B
的__加__
方法A
被调用b
作为参数。 -
__ __ RADD
:反映增加;为A + B
,的
是调用__ RADD __
B法A
作为一个实例。这仅用于在A
不知道该怎么办的添加和两个对象是不同的类型。 -
__ __ IADD
:就地增加;用于A + = B
其中结果被分配回左边的变量。此分开设置,因为它有可能实现它在一个更有效的方式。例如,如果A
是一个列表,那么A + = B
相同a.extend(二)
。然而,在C = A +的情况B
你必须做出的一个副本A
,然后扩展它,因为A
是不是可以在这种情况下修改。需要注意的是,如果你不执行__ IADD __
则Python会只是调用__添加__
代替。
__add__
: adds two items (+
operator). When you doa + b
, the__add__
method ofa
is called withb
as an argument.__radd__
: reflected add; fora + b
, the__radd__
method ofb
is called witha
as an instance. This is only used whena
doesn't know how to do the add and the two objects are different types.__iadd__
: in-place add; used fora += b
where the result is assigned back to the left variable. This is provided separately because it might be possible to implement it in a more efficient way. For example, ifa
is a list, thena += b
is the same asa.extend(b)
. However, in the case ofc = a + b
you have to make a copy ofa
before you extend it sincea
is not to be modified in this case. Note that if you don't implement__iadd__
then Python will just call__add__
instead.
所以,因为这些不同的操作是有独立的方法来实现,这是可能的(但一般不好的做法)来实现他们,让他们做完全不同的事情,或者在这种情况下,只有略的不同的事情
So since these different operations are implemented with separate methods, it is possible (but generally bad practice) to implement them so they do totally different things, or perhaps in this case, only slightly different things.
还有人推断,你使用numpy的,并解释其行为。但是,你问的底层实现。希望你现在看到的为什么的,有时的情况是 A + = B
是不一样的 A = A + b
。顺便说一下,一个类似的方法三人也可以用于其它操作来实现。请参见为所有支持就地方法的列表。
Others have deduced that you're using NumPy and explained its behavior. However, you asked about the underlying implementation. Hopefully you now see why it is sometimes the case that a += b
is not the same as a = a + b
. By the way, a similar trio of methods may also be implemented for other operations. See this page for a list of all the supported in-place methods.
这篇关于Python的增量赋值问题的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!