基本上,
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 it5
通过执行操作,您始终可以看到内存中指向的位置
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. >>> b5
您可以使用
copy,当你想要做一个结构的副本。但是,它
仍然不会复制被 拘禁 的东西
。这包括整数小于
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
切片列表(无论何时使用
:)都会复制一份。



