Python增强赋值问题 [英] Python augmented assignment issue

查看:45
本文介绍了Python增强赋值问题的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我遇到了一些关于 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 + b,以a为例调用b__radd__方法.这仅在 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.

这篇关于Python增强赋值问题的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆