為什么+=在列表上表現(xiàn)得出乎意料?這個+=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 回答

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
提交
取消