operator + =与collections.Counter的行为不一致

Grz*_*ała 2 python collections operator-keyword

In [20]: from collections import Counter

In [21]: x = [Counter()]

In [22]: z = x[0]

In [23]: z.update("w")

In [24]: z
Out[24]: Counter({'w': 1})

In [25]: x
Out[25]: [Counter({'w': 1})]

In [26]: z += Counter(["q"])

In [27]: z
Out[27]: Counter({'q': 1, 'w': 1})

In [28]: x
Out[28]: [Counter({'w': 1})]
Run Code Online (Sandbox Code Playgroud)

我原x以为是[Counter({'q': 1, 'w': 1})].怎么了?

zon*_*ndo 5

x += yx只有x__iadd__方法才会影响另一个引用.如果它只是__add__,恰恰x += y相当于x = x + y. collections.Counter是什么,它具备__iadd__的,但确实有__add__.因此,与之z += ...相同z = z + ...,您只需重新定义z而不是修改对象.(我通过使用help(collections.Counter)和搜索找到了__iadd__它.它没有它.)