gpt4 book ai didi

python - 使用 frozenset 的增强赋值

转载 作者:行者123 更新时间:2023-11-28 22:30:40 24 4
gpt4 key购买 nike

我刚刚在卡住集上尝试了增广赋值,结果让我吃惊:

>>> x = frozenset(['foo', 'bar', 'baz'])
>>> x
frozenset({'foo', 'baz', 'bar'})
>>> x &= {'baz', 'qux', 'quux'}
>>> x
frozenset({'baz'})

这不应该发生,是吗? frozensets 不是不可变的吗?

最佳答案

你为什么感到惊讶?

您知道术语“扩充赋值”,所以找到 "Python Data Model on augmented arithmetic assignments" 没有问题(强调我的):

These [__i***__] methods should attempt to do the operation in-place (modifying self) and return the result (which could be, but does not have to be, self). If a specific method is not defined, the augmented assignment falls back to the normal methods. For instance, if x is an instance of a class with an __iadd__() method, x += y is equivalent to x = x.__iadd__(y) . Otherwise, x.__add__(y) and y.__radd__(x) are considered, [...]

>>> x = frozenset(['foo', 'bar', 'baz'])
>>> x.__iand__
[...]
AttributeError: 'frozenset' object has no attribute '__iand__'

所以它没有__iand__ 方法所以你执行的代码是:

>>> x = x & {'baz', 'qux', 'quux'}

不过,__and__ 方法是由 frozenset 定义的:

>>> x & {'baz', 'qux', 'quux'}
frozenset({'baz'})

但是您丢失了对原始 frozenset 的引用:x:

>>> y = x   # that doesn't do a copy, it's just to check if `x` has changed"
>>> x &= {'baz', 'qux', 'quux'}
>>> x is y # check if they reference the same object!
False
>>> x, y
(frozenset({'baz'}), frozenset({'bar', 'baz', 'foo'}))

但这只是在 "Principle of least astonishment" 之后.您想要 __and__ 并且明确表示不想保留原来的 x - 就地操作也会改变它!

再说一遍:为什么这让您感到惊讶?

关于python - 使用 frozenset 的增强赋值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42048174/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com