问题描述
我遇到了关于 python 增强赋值的一些有趣的事情 +=
i ran into something interesting about the python augmented assignment +=
如果 a 是更简单"的数据类型,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
未完成转换的情况
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:
__add__
:添加两项(+
运算符).当你执行a + b
时,a
的__add__
方法会以b
作为参数来调用.李>__radd__
:反射添加;对于a + b
,b
的__radd__
方法以a
为实例调用.这仅在a
不知道如何添加并且两个对象是不同类型时使用.__iadd__
:就地添加;用于a += b
将结果分配回左侧变量.这是单独提供的,因为它可能以更有效的方式实现.例如,如果a
是一个列表,则a += b
与a.extend(b)
相同.但是,在c = a + b
的情况下,您必须在扩展之前制作a
的副本,因为a
不是在这种情况下进行了修改.请注意,如果您不实现__iadd__
,那么 Python 只会调用__add__
.
__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增强分配问题的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持跟版网!