相关疑难解决方法(0)

为什么+ =在列表上出现意外行为?

+=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)

python augmented-assignment

103
推荐指数
6
解决办法
6万
查看次数

在python中+ =做到了什么?

我需要知道python中的+ =做了什么.就这么简单.我也很感激链接到python中其他简写工具的定义.

python operators notation shorthand compound-assignment

103
推荐指数
9
解决办法
50万
查看次数

在Python中使用+和+ =运算符进行串联

最近,我发现串联列表时出现不一致。

因此,如果我使用+运算符,它不会将list与不同类型的任何对象连接在一起。例如,

l = [1,2,3]
l = l + (4,5)        #TypeError: can only concatenate list (not "tuple") to list
Run Code Online (Sandbox Code Playgroud)

但是,如果使用+ =运算符,它将忽略对象的类型。例如,

l = [1,2,3]
l += "he"            #Here, l becomes [1, 2, 3,"h", "e"]

l += (56, 67)        #Here, l becomes [1, 2, 3,"h", "e", 56, 67]
Run Code Online (Sandbox Code Playgroud)

那么,这仅仅是语言的语义还是其他原因?

python list concatenation python-3.x

38
推荐指数
1
解决办法
959
查看次数