python byRef // copy

前端 未结 4 1605
花落未央
花落未央 2021-01-05 16:52

I am new to Python (and dont know much about programming anyway), but I remember reading that python generally does not copy values so any statement a = b makes b point to a

4条回答
  •  渐次进展
    2021-01-05 17:29

    No, the result should be 1.

    Think of the assignment operator ( = ) as the assignment of a reference.

    a = 1 #a references the integer object 1
    b = a #b and a reference the same object
    a = 2 #a now references a new object (2)
    print b # prints 1 because you changed what a references, not b
    

    This whole distinction really is most important when dealing with mutable objects such as lists as opposed to immutable objects like int,float and tuple.

    Now consider the following code:

    a=[]  #a references a mutable object
    b=a   #b references the same mutable object
    b.append(1)  #change b a little bit
    print a # [1] -- because a and b still reference the same object 
            #        which was changed via b.
    

提交回复
热议问题