我想我开始理解python了,但是我仍然有一个基本的问题。什么时候使用copy.copy?
>>>a=5
>>>b=a
>>>a=6
>>>print b
5Ok说得通。但是,在什么情况下,说b=a在a和b之间形成了某种“联系”,这样修改a就会修改b?这就是我对copy.copy不太理解的地方--是否每次将一个带等号的变量赋给另一个变量时,只是复制值?
发布于 2011-08-13 06:39:16
基本上,b = a将b指向a所指向的任何位置,而不指向其他任何位置。
您所问的是可变类型。数字、字符串、元组、冻结集、布尔值、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。但是,it 仍然不会复制 的内容。这包括小于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对列表进行切片(无论何时使用:)都会生成一个副本。
发布于 2011-08-13 06:38:05
任务永远不会复制。它只是将a引用的对象(为了坚持本例)链接到b。a和b引用相同的对象,直到您更改其中一个的链接。
去掉“变量”这个术语很有用,它只是你放在一个对象上的一个标签,一个你可以用来连接这个对象的句柄,仅此而已。
copy.copy根本不会改变这一点。
如果您想传播更改,即使是数字或字符串-这里显示的是不变性-您必须将数字和字符串包装在另一个对象中,并将其分配给a和b。
如果您想要进行相反的操作,则必须使用copy模块,但请确保阅读文档。但是你必须考虑对象,而不是变量。
https://stackoverflow.com/questions/7046971
复制相似问题