Python a, b = b, a +b

前端 未结 7 2218
独厮守ぢ
独厮守ぢ 2020-11-28 07:24

This is my first question and I started to learn Python. Is there a difference between:

a, b = b, a + b

and

a = b
b = a +          


        
7条回答
  •  天涯浪人
    2020-11-28 08:11

    The line:

    a, b = b, a + b
    

    is closer to:

    temp_a = a
    a = b
    b = temp_a + b
    

    where b is using the old value of a before a was reassigned to the value of b.

    Python first evaluates the right-hand expression and stores the results on the stack, then takes those two values and assigns them to a and b. That means that a + b is calculated before a is changed.

    See How does swapping of members in the python tuples (a,b)=(b,a) work internally? for the low-down on how this all works, at the bytecode level.

提交回复
热议问题