Multiple assignment and evaluation order in Python

前端 未结 10 1904
醉酒成梦
醉酒成梦 2020-11-22 01:41

What is the difference between the following Python expressions:

# First:

x,y = y,x+y

# Second:

x = y
y = x+y

First gives diffe

10条回答
  •  执念已碎
    2020-11-22 02:26

    An observation regarding the left-hand side as well: the order of assignments is guaranteed to be the order of their appearance, in other words:

    a, b = c, d
    

    is equivalent functionally to precisely (besides t creation):

    t = (c, d)
    a = t[0] # done before 'b' assignment
    b = t[1] # done after 'a' assignment
    

    This matters in cases like object attribute assignment, e.g.:

    class dummy:
        def __init__(self): self.x = 0
    
    a = dummy(); a_save = a
    a.x, a = 5, dummy()
    print(a_save.x, a.x) # prints "5 0" because above is equivalent to "a = dummy(); a_save = a; t = (5, dummy()); a.x = t[0]; a = t[1]"
    
    a = dummy(); a_save = a
    a, a.x = dummy(), 5
    print(a_save.x, a.x) # prints "0 5" because above is equivalent to "a = dummy(); a_save = a; t = (dummy(), 5); a = t[0]; a.x = t[1]"
    

    This also implies that you can do things like object creation and access using one-liners, e.g.:

    class dummy:
        def __init__(self): self.x = 0
    # Create a = dummy() and assign 5 to a.x
    a, a.x = dummy(), 5
    

提交回复
热议问题