Python"a = ab"和"a- = b"真的相同吗?

Fra*_*lli 3 python

它似乎a = a-b不同a -= b,我不知道为什么.

码:

cache = {}
def part(word):
    if word in cache:
        return cache[word]
    else:
        uniq = set(word)
        cache[word] = uniq
        return uniq

w1 = "dummy"
w2 = "funny"

# works
test = part(w1)
print(test)
test = test-part(w2)
print(test)
print(cache)

# dont't works
test = part(w1)
print(test)
test -= part(w2) # why it touches "cache"?
print(test)
print(cache)
Run Code Online (Sandbox Code Playgroud)

结果:

set(['y', 'm', 'u', 'd'])
set(['m', 'd'])
{'dummy': set(['y', 'm', 'u', 'd']), 'funny': set(['y', 'n', 'u', 'f'])}
set(['y', 'm', 'u', 'd'])
set(['d', 'm'])
{'dummy': set(['d', 'm']), 'funny': set(['y', 'n', 'u', 'f'])}
Run Code Online (Sandbox Code Playgroud)

如您所见,第三行和最后一行不同.为什么在第二种情况下变量"缓存"是不同的?test -= part(w2)不喜欢test = test-part(w2)

编辑1 - 感谢您的答案,但为什么var会cache发生变化?

Gar*_*tty 6

a = a - b是一个取代a新对象的操作 - 结果a - b.

a -= b是一种a在就地操作并使用它修改它的操作b.

在某些方面,这两个是等价的,而在另一些方面,它们不是.显而易见的情况是不可变对象,它们的行为相同.在可变对象上,正如您所发现的那样,存在很大差异.


NPE*_*NPE 6

是的,他们是不同的.比较以下内容:

>>> x = set([1,2,3])
>>> y = x
>>> y -= set([1])
>>> x
set([2, 3])

>>> map(id, (x, y))
[18641904, 18641904]
Run Code Online (Sandbox Code Playgroud)

>>> x = set([1,2,3])
>>> y = x
>>> y = y - set([1])
>>> x
set([1, 2, 3])

>>> map(id, (x, y))
[2774000, 21166000]
Run Code Online (Sandbox Code Playgroud)

换句话说,y -= set(...)变化y到位.由于两个xy指向同一个对象,他们都改变.

另一方面,y = y - set(...)创建一个新对象,重新绑定y以引用此新对象.x不受影响,因为它仍然指向旧对象.