相关疑难解决方法(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万
查看次数

+和+ =运算符不同?

>>> c = [1, 2, 3]
>>> print(c, id(c))
[1, 2, 3] 43955984
>>> c += c
>>> print(c, id(c))
[1, 2, 3, 1, 2, 3] 43955984
>>> del c
>>> c = [1, 2, 3]
>>> print(c, id(c))
[1, 2, 3] 44023976
>>> c = c + c
>>> print(c, id(c))
[1, 2, 3, 1, 2, 3] 26564048
Run Code Online (Sandbox Code Playgroud)

有什么不同?是+ =和+不应该仅仅是语法糖?

python list operators

4
推荐指数
1
解决办法
457
查看次数