为什么+=在列表上表现得出乎意料?这个+=python中的运算符似乎意外地在列表上操作。有人能告诉我这是怎么回事吗?class foo:
bar = []
def __init__(self,x):
self.bar += [x]class foo2:
bar = []
def __init__(self,x):
self.bar = self.bar + [x]f = foo(1)g = foo(2)print f.barprint g.bar
f.bar += [3]print f.barprint g.bar
f.bar = f.bar + [4]print f.barprint g.bar
f = foo2(1)g = foo2(2)print f.bar
print g.bar输出量[1, 2][1, 2][1, 2, 3][1, 2, 3][1, 2, 3, 4][1, 2, 3][1][2]foo += bar似乎影响到类的每个实例,而foo = foo + bar看上去就像我所期望的那样。这个+=运算符被称为“复合赋值运算符”。
3 回答
![?](http://img1.sycdn.imooc.com/533e4c9c0001975102200220-100-100.jpg)
POPMUISE
TA贡献1765条经验 获得超5个赞
+=
__iadd__
__add__
__iadd__
__add__
+
+=
__iadd__
__add__
+=
a += b
a = a + b
).
__iadd__
__add__
a += b
__iadd__
a
a = a + b
a
>>> a1 = a2 = [1, 2]>>> b1 = b2 = [1, 2]>>> a1 += [3] # Uses __iadd__, modifies a1 in-place>>> b1 = b1 + [3] # Uses __add__, creates new list, assigns it to b1>>> a2[1, 2, 3] # a1 and a2 are still the same list>>> b2[1, 2] # whereas only b1 was changed
__iadd__
) a += b
a = a + b
+=
+=
添加回答
举报
0/150
提交
取消