+=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.bar
print g.bar
f.bar += [3]
print f.bar
print g.bar
f.bar = f.bar + [4]
print f.bar
print g.bar
f = foo2(1)
g = foo2(2)
print f.bar
print g.bar
Run Code Online (Sandbox Code Playgroud)
OUTPUT
[1, 2]
[1, 2]
[1, 2, 3]
[1, 2, 3]
[1, 2, 3, 4]
[1, 2, 3]
[1]
[2] …Run Code Online (Sandbox Code Playgroud) 考虑以下代码:
>>> x = y = [1, 2, 3, 4]
>>> x += [4]
>>> x
[1, 2, 3, 4, 4]
>>> y
[1, 2, 3, 4, 4]
Run Code Online (Sandbox Code Playgroud)
然后考虑这个:
>>> x = y = [1, 2, 3, 4]
>>> x = x + [4]
>>> x
[1, 2, 3, 4, 4]
>>> y
[1, 2, 3, 4]
Run Code Online (Sandbox Code Playgroud)
为什么这两个有区别?
(是的,我试着寻找这个).
>>> b = []
>>> c = '1234'
>>> b += c
>>> b
['1', '2', '3', '4']
>>>
Run Code Online (Sandbox Code Playgroud)
这里发生了什么?这应该不行,对吗?还是我错过了一些明显的东西?
>>> b = []
>>> c = '1234'
>>> b + c
Traceback (most recent call last):
File "<pyshell#7>", line 1, in <module>
b + c
TypeError: can only concatenate list (not "str") to list
>>>
Run Code Online (Sandbox Code Playgroud)
然后a += b 并不总是等同于a = a + b?
我认为list.extend列表中的"+ ="基本上做同样的事情 - 扩展列表而不创建新列表.
我希望下面的代码可以打印,[42, 43, 44, 45, 46]但我得到了UnboundLocalError: local variable 'x' referenced before assignment
为什么我收到此错误?区别在哪里?
def f():
x.extend([43, 44])
def g():
x += ([45, 46])
x = [42]
f()
g()
print x
Run Code Online (Sandbox Code Playgroud)
我在python2.7.3和python3.4.0中尝试过这个.