基本上,b = a将b指向a所指向的地方,而不是其他任何内容。
你问的是可变类型。数字,字符串,元组,frozensets,布尔值,None是不可变的。列表,字典,集合,字节数组是可变的。
如果我创建一个可变类型,如list:
>>> a = [1, 2] # create an object in memory that points to 1 and 2, and point a at it
>>> b = a # point b to wherever a points
>>> a[0] = 2 # change the object that a points to by pointing its first item at 2
>>> a
[2, 2]
>>> b
[2, 2]他们两个仍然指向同一个项目。
我也会评论你的原始代码:
>>>a=5 # '5' is interned, so it already exists, point a at it in memory
>>>b=a # point b to wherever a points
>>>a=6 # '6' already exists in memory, point a at it
>>>print b # b still points at 5 because you never moved it
5通过执行id(something),您始终可以看到内存中指向的位置。
>>> id(5)
77519368
>>> a = 5
>>> id(a)
77519368 # the same as what id(5) showed us, 5 is interned
>>> b = a
>>> id(b)
77519368 # same again
>>> id(6)
77519356
>>> a = 6
>>> id(a)
77519356 # same as what id(6) showed us, 6 is interned
>>> id(b)
77519368 # still pointing at 5.
>>> b
5如果要复制结构,请使用copy。但是,它仍然不会制作interned的副本。这包括小于256,True,False,None,a等短字符串的整数。基本上,你几乎不应该使用它,除非你确定你不会被实习搞砸。
再考虑一个例子,即使使用可变类型,将一个变量指向一个新的仍然不会改变旧变量:
>>> a = [1, 2]
>>> b = a
>>> a = a[:1] # copy the list a points to, starting with item 2, and point a at it
>>> b # b still points to the original list
[1, 2]
>>> a
[1]
>>> id(b)
79367984
>>> id(a)
80533904切片列表(无论何时使用:)都会复制。