Python Assignment Operator Precedence - (a, b) = a[b] = {}, 5

谁都会走 提交于 2019-11-26 09:50:43

问题


I saw this Python snippet on Twitter and was quite confused by the output:

>>> a, b = a[b] = {}, 5
>>> a
{5: ({...}, 5)}

What is going on here?


回答1:


From the Assignment statements documentation:

An assignment statement evaluates the expression list (remember that this can be a single expression or a comma-separated list, the latter yielding a tuple) and assigns the single resulting object to each of the target lists, from left to right.

You have two assignment target lists; a, b, and a[b], the value {}, 5 is assigned to those two targets from left to right.

First the {}, 5 tuple is unpacked to a, b. You now have a = {} and b = 5. Note that {} is mutable.

Next you assign the same dictionary and integer to a[b], where a evaluates to the dictionary, and b evaluates to 5, so you are setting the key 5 in the dictionary to the tuple ({}, 5) creating a circular reference. The {...} thus refers to the same object that a is already referencing.

Because assignment takes place from left to right, you can break this down to:

a, b = {}, 5
a[b] = a, b

so a[b][0] is the same object as a:

>>> a, b = {}, 5
>>> a[b] = a, b
>>> a
{5: ({...}, 5)}
>>> a[b][0] is a
True


来源:https://stackoverflow.com/questions/32127908/python-assignment-operator-precedence-a-b-ab-5

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!