>>> class Sample:
def __init__(self, num):
self.num = num
self.id = id(self)
>>> s1 = Sample(1)
>>> s2 = Sample(2)
>>> listOne = [s1, s2]
>>> listOne[0].num
1
>>> listOne[0].id
88131696
>>> listOne[1].num
2
>>> listOne[1].id
92813904
# so far we know that listOne contains these unique objects
>>> listTwo = listOne
>>> listTwo[0].num
1
>>> listTwo[0].id
88131696
>>> listTwo[1].num
2
>>> listTwo[1].id
92813904
# well shoot, the two lists have the same objects!
# another way to do show that is to simply print the lists
>>> listOne
[<__main__.Sample object at 0x0540C870>, <__main__.Sample object at 0x05883A50>]
>>> listTwo
[<__main__.Sample object at 0x0540C870>, <__main__.Sample object at 0x05883A50>]
# those odd number sequences are hexadecimal and represent the memory location
# to prove the point further, you can use the built in hex() with id()
>>> hex(listOne[0].id) # id is 88131696 from above
'0x540c870'
在Python中,所有的东西都是一个对象,这意味着所有的东西都有自己的内存。在
初始化
listOne = [1, 2, 3]
时,会给它一个内存地址。在然后使用赋值运算符
=
将listOne
的内存位置分配给listTwo
。在如果我们以你为例:
我们可以:
^{2}$有人提到你可以使用切片运算符
:
,但这给了你一个浅拷贝。如果您不熟悉浅拷贝和深拷贝的区别,请阅读这些docs。基本上,浅拷贝是一个新的外部容器对象([ ]
),内部元素是对相同内存位置的引用。深度复制也是一个新的外部容器,但它会获得内部对象的全新副本(即对象的相同副本,但位于新的内存位置)。在我给你留一个非灵长类的浅拷贝的例子(例如,不像你的
int
):相关问题 更多 >
编程相关推荐