标签:
在python中,对象赋值实际上是对象的引用。当创建一个对象,然后把它赋给另一个变量的时候,python并没有拷贝这个对象,而只是拷贝了这个对象的引用。
赋值其实只是传递对象引用,引用对象id是一样的。原始列表改变,被赋值的b也会做相同的改变。
1
2
3
4
5
6
7
8
9
10
11
12
13
|
>>> alist = [ 1 , 2 , 3 ,[ "a" , "b" ]] >>> b = alist >>> print (b) [ 1 , 2 , 3 , [ ‘a‘ , ‘b‘ ]] >>> alist.append( 5 ) >>> alist = [ 1 , 2 , 3 ,[ "a" , "b" ]] >>> b = alist >>> print (b) [ 1 , 2 , 3 , [ ‘a‘ , ‘b‘ ]] >>> alist.append( 5 ) >>> print (alist); print (b) [ 1 , 2 , 3 , [ ‘a‘ , ‘b‘ ], 5 ] [ 1 , 2 , 3 , [ ‘a‘ , ‘b‘ ], 5 ] |
浅拷贝是指拷贝的只是原始对象元素的引用,换句话说,浅拷贝产生的对象本身是新的,但是它的内容不是新的,只是对原对象的一个引用。
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
|
>>> import copy >>> alist = [ 1 , 2 , 3 ,[ "a" , "b" ]] >>> c = copy.copy(alist) >>> print (alist); print (c) [ 1 , 2 , 3 , [ ‘a‘ , ‘b‘ ]] [ 1 , 2 , 3 , [ ‘a‘ , ‘b‘ ]] >>> alist.append( 5 ) >>> print (alist); print (c) [ 1 , 2 , 3 , [ ‘a‘ , ‘b‘ ], 5 ] [ 1 , 2 , 3 , [ ‘a‘ , ‘b‘ ]] >>> alist[ 3 ] [ ‘a‘ , ‘b‘ ] >>> alist[ 3 ].append( ‘cccc‘ ) >>> print (alist); print (c) [ 1 , 2 , 3 , [ ‘a‘ , ‘b‘ , ‘cccc‘ ], 5 ] [ 1 , 2 , 3 , [ ‘a‘ , ‘b‘ , ‘cccc‘ ]] #里面的子对象被改变了 |
浅copy的几种方式:
1
2
3
4
|
>>> alist = [ 1 , 2 , 3 ,[ "a" , "b" ]] >>> c = alist[:] >>> print (c) [ 1 , 2 , 3 , [ ‘a‘ , ‘b‘ ]] |
1
2
3
4
|
>>> alist = [ 1 , 2 , 3 ,[ "a" , "b" ]] >>> c = list (alist) >>> print (c) [ 1 , 2 , 3 , [ ‘a‘ , ‘b‘ ]] |
1
2
3
4
|
>>> alist = [ 1 , 2 , 3 ,[ "a" , "b" ]] >>> c = copy.copy(alist) >>> print (c) [ 1 , 2 , 3 , [ ‘a‘ , ‘b‘ ]] |
深拷贝是指完全拷贝原始对象,而且产生的对象是新的,并且不受其他引用对象的操作影响。
深copy:
Names2 = copy.deepcopy(names)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
|
>>> import copy >>> alist = [ 1 , 2 , 3 ,[ "a" , "b" ]] >>> d = copy.deepcopy(alist) >>> print (alist); print (d) [ 1 , 2 , 3 , [ ‘a‘ , ‘b‘ ]] [ 1 , 2 , 3 , [ ‘a‘ , ‘b‘ ]]始终没有改变 >>> alist.append( 5 ) >>> print (alist); print (d) [ 1 , 2 , 3 , [ ‘a‘ , ‘b‘ ], 5 ] [ 1 , 2 , 3 , [ ‘a‘ , ‘b‘ ]]始终没有改变 >>> alist[ 3 ] [ ‘a‘ , ‘b‘ ] >>> alist[ 3 ].append( "ccccc" ) >>> print (alist); print (d) [ 1 , 2 , 3 , [ ‘a‘ , ‘b‘ , ‘ccccc‘ ], 5 ] [ 1 , 2 , 3 , [ ‘a‘ , ‘b‘ ]] 始终没有改变 |
标签:
原文地址:http://www.cnblogs.com/wangsen-123/p/5731022.html