相关疑难解决方法(0)

为什么Java的+ =, - =,*=,/ =复合赋值运算符需要转换?

直到今天,我还以为:

i += j;
Run Code Online (Sandbox Code Playgroud)

只是一个捷径:

i = i + j;
Run Code Online (Sandbox Code Playgroud)

但是如果我们试试这个:

int i = 5;
long j = 8;
Run Code Online (Sandbox Code Playgroud)

然后i = i + j;将不会编译但i += j;将编译正常.

这是否意味着事实上i += j;是这样的捷径 i = (type of i) (i + j)

java casting operators variable-assignment assignment-operator

3547
推荐指数
11
解决办法
28万
查看次数

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

+=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:a + = b与a = a + b不同

可能重复:
Python中的加号等于(+ =)做什么?

今天我发现了python语言的一个有趣的"特性",这给了我很多悲伤.

>>> a = [1, 2, 3]
>>> b = "lol"
>>> a = a + b 
TypeError: can only concatenate list (not "str") to list
>>> a += b
>>> a
[1, 2, 3, 'l', 'o', 'l']
Run Code Online (Sandbox Code Playgroud)

那个怎么样?我以为这两个本来是相同的!更糟糕的是,这是我有一段时间调试的代码

>>> a = [1, 2, 3]
>>> b = {'omg': 'noob', 'wtf' : 'bbq'}
>>> a = a + b
TypeError: can only concatenate list (not "dict") to list
>>> a += b
>>> a
[1, 2, 3, …
Run Code Online (Sandbox Code Playgroud)

python

36
推荐指数
2
解决办法
2万
查看次数