它们不必相同。
使用
+运算符调用方法,
__add__而使用
+=运算符调用
__iadd__。完全取决于所讨论的对象,当调用这些方法之一时会发生什么。
如果使用
x += y但
x不提供
__iadd__方法(或方法返回
NotImplemented),
__add__则用作 后备
,即
x = x + y会发生这种情况。
对于列表,使用
l +=iterable实际
l使用的元素扩展列表
iterable。在您的情况下,字符串(可迭代)中的每个字符都会在
extend操作过程中附加。
演示1:使用
__iadd__
>>> l = []>>> l += 'table'>>> l['t', 'a', 'b', 'l', 'e']
演示2:使用方法
extend相同
>>> l = []>>> l.extend('table')>>> l['t', 'a', 'b', 'l', 'e']演示3:添加列表和字符串会引发
TypeError。
>>> l = []>>> l = l + 'table'[...]TypeError: can only concatenate list (not "str") to list
不使用
+=将为您提供
TypeError这里的信息,因为仅
__iadd__实现了扩展行为。
演示4:常见陷阱:
+=不建立新列表。我们可以通过与
is操作员检查相同的对象身份来确认这一点。
>>> l = []>>> l_ref = l # another name for l, no data is copied here>>> l += [1, 2, 3] # uses __iadd__, mutates l in-place>>> l is l_ref # confirm that l and l_ref are names for the same objectTrue>>> l[1, 2, 3]>>> l_ref # mutations are seen across all names[1, 2, 3]
但是,
l = l + iterable语法确实会建立一个新列表。
>>> l = []>>> l_ref = l # another name for l, no data is copied here>>> l = l + [1, 2, 3] # uses __add__, builds new list and reassigns name l>>> l is l_ref # confirm that l and l_ref are names for different objectsFalse>>> l[1, 2, 3]>>> l_ref[]
在某些情况下,这可能会产生细微的错误,因为会
+=更改 原始列表,同时
l = l + iterable会构建 新 列表并 重新分配 名称
l。
奖金
Ned
Batchelder在文档中找到这个的挑战


![i = i + n是否真的与i + = n相同?[重复] i = i + n是否真的与i + = n相同?[重复]](http://www.mshxw.com/aiimages/31/668107.png)
