How does this chain assignment work?

帅比萌擦擦* 提交于 2020-01-11 09:43:28

问题


Consider the following code; it is a bad programming practice. I am wondering why the resulting list A is [1, 1, 3] rather than [1, 2, 1]. From the view of Java, the result should be [1, 2, 1]. Can anyone explain why this result is what it is?

A = [1, 2, 3]
t = 2
t = A[t] = A.count(3)

After evaluation, A is [1, 1, 3] and t is 1.

My Python version is 3.3.


回答1:


On line 3 you have a chained assignment

t = A[t] = A.count(3)

t = A.count(3) is evaluated first – t set to the return value of A.count(3) which in this case is 1. Then the member of A at index t(=1) is set to the return value of A.count(3), which is still 1.

Read more about chained assignments in Python here




回答2:


A.count(3) yields 1.

t = 1 is executed first. Now t is 1.

A[t] = 1 is executed. (A[1] = 1)


>>> class Demo:
...     def __setitem__(self, idx, value):
...         print 'Set index', idx
... 
>>> d = Demo()
>>> d[1] = d[2] = 2
Set index 1
Set index 2



回答3:


Haha... The python evaluation of such expression in not as obvious as you may expect from the t = A[t] = A.count(3) expression. In first step the value at the end is evaluated with is 1. Then it is first assigned to t and then to A[t], but at this time t is 1.

Suggestion by @Henrik to read about chained assignments is very good.

Actually, your example self-explain why it is perceived as bad programming practice.



来源:https://stackoverflow.com/questions/17740639/how-does-this-chain-assignment-work

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