Are python variables pointers? or else what are they?

前端 未结 9 2052
借酒劲吻你
借酒劲吻你 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:47

    Assignment doesn't modify objects; all it does is change where the variable points. Changing where one variable points won't change where another one points.

    You are probably thinking of the fact that lists and dictionaries are mutable types. There are operators to modify the actual objects in-place, and if you use one of those, you will see the change in all variables pointing to the same object:

    x = []
    y = x
    x.append(1)
    # x and y both are now [1]
    

    But assignment still just moves the pointer around:

    x = [2]
    # x now points to new list [2]; y still points to old list [1]
    

    Numbers, unlike dictionaries and lists, are immutable. If you do x = 3; x += 2, you aren't transforming the number 3 into the number 5; you're just making the variable x point to 5 instead. The 3 is still out there unchanged, and any variables pointing to it will still see 3 as their value.

    (In the actual implementation, numbers are probably not reference types at all; it's more likely that the variables actually contain a representation of the value directly rather than pointing to it. But that implementation detail doesn't change the semantics where immutable types are concerned.)

提交回复
热议问题