Python增强分配问题

2022-01-17 00:00:00 python numpy arrays numbers complex-numbers

问题描述

我遇到了关于 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 += ba = 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 + bb__radd__ 方法以 a 为实例调用.这仅在 a 不知道如何添加并且两个对象是不同类型时使用.
  • __iadd__:就地添加;用于 a += b 将结果分配回左侧变量.这是单独提供的,因为它可能以更有效的方式实现.例如,如果 a 是一个列表,则 a += ba.extend(b) 相同.但是,在 c = a + b 的情况下,您必须在扩展之前制作 a 的副本,因为 a 不是在这种情况下进行了修改.请注意,如果您不实现 __iadd__,那么 Python 只会调用 __add__.
  • __add__: adds two items (+ operator). When you do a + b, the __add__ method of a is called with b as an argument.
  • __radd__: reflected add; for a + b, the __radd__ method of b is called with a as an instance. This is only used when a doesn't know how to do the add and the two objects are different types.
  • __iadd__: in-place add; used for a += 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, if a is a list, then a += b is the same as a.extend(b). However, in the case of c = a + b you have to make a copy of a before you extend it since a 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 += ba = 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.

相关文章