何时使用copy.copy


问题内容

我认为我已经开始了解python,但仍然遇到基本问题。什么时候使用copy.copy

>>>a=5
>>>b=a
>>>a=6
>>>print b
5

好吧
但是在什么情况下,话语b=a在a和b之间形成某种“链接”,从而修改a会修改b?这不是我要解决的问题copy.copy–每次将一个等号分配给另一个变量时,是否只会复制该值?


问题答案:

基本上,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,当你想要做一个结构的副本。但是,它
仍然不会复制被 拘禁 的东西
。这包括整数小于256TrueFalseNone,短字符串喜欢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

切片列表(无论何时使用:)都会复制一份。