How does this chain assignment work?

前端 未结 3 1396
北海茫月
北海茫月 2021-01-20 03:57

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]

3条回答
  •  别那么骄傲
    2021-01-20 04:54

    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
    

提交回复
热议问题