Are python variables pointers? or else what are they?

前端 未结 9 2008
借酒劲吻你
借酒劲吻你 2020-11-22 07:01

Variables in Python are just pointers, as far as I know.

Based on this rule, I can assume that the result for this code snippet:

i = 5
j = i
j = 3          


        
9条回答
  •  不知归路
    2020-11-22 07:56

    Python variables are names bound to objects

    From the docs:

    Names refer to objects. Names are introduced by name binding operations. Each occurrence of a name in the program text refers to the binding of that name established in the innermost function block containing the use.

    When you do

    i = 5
    j = i
    

    that's the same as doing:

    i = 5
    j = 5
    

    j doesn't point to i, and after the assignment, j doesn't know that i exists. j is simply bound to whatever i was pointing to at the time of assignment.

    If you did the assignments on the same line, it would look like this:

    i = j = 5
    

    And the result would be exactly the same.

    Thus, later doing

    i = 3
    

    doesn't change what j is pointing to - and you can swap it - j = 3 would not change what i is pointing to.

    Your example doesn't remove the reference to the list

    So when you do this:

    i = [1,2,3]
    j = i
    

    It's the same as doing this:

    i = j = [1,2,3]
    

    so i and j both point to the same list. Then your example mutates the list:

    i[0] = 5
    

    Python lists are mutable objects, so when you change the list from one reference, and you look at it from another reference, you'll see the same result because it's the same list.

提交回复
热议问题