Python中,对象的赋值,拷贝(深/浅拷贝)之间是有差异的,如果使用的时候不注意,就可能产生意外的结果。
下面本文就通过简单的例子介绍一下这些概念之间的差别。
对象赋值
直接看一段代码:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
|
will
=
[
"Will"
,
28
,
[
"Python"
,
"C#"
,
"JavaScript"
]
]
wilber
=
will
print
id
(
will
)
print
will
print
[
id
(
ele
)
for
ele
in
will
]
print
id
(
wilber
)
print
wilber
print
[
id
(
ele
)
for
ele
in
wilber
]
will
[
0
]
=
"Wilber"
will
[
2
]
.
append
(
"CSS"
)
print
id
(
will
)
print
will
print
[
id
(
ele
)
for
ele
in
will
]
print
id
(
wilber
)
print
wilber
print
[
id
(
ele
)
for
ele
in
wilber
]
|
代码的输出为:
下面来分析一下这段代码:
常见的可变类型和不可变类型主要有如下,下面将会涉及部分知识:
可变类型:列表、字典
不可变类型:数字、字符串、元组
可以理解为,Python中,对象的赋值都是进行对象引用(内存地址)传递
这里需要注意的一点是,str是不可变类型,所以当修改的时候会替换旧的对象,(进行新的内存分配)产生一个新的地址39758496
浅拷贝
下面就来看看浅拷贝的结果:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
|
import
copy
will
=
[
"Will"
,
28
,
[
"Python"
,
"C#"
,
"JavaScript"
]
]
wilber
=
copy
.
copy
(
will
)
print
id
(
will
)
print
will
print
[
id
(
ele
)
for
ele
in
will
]
print
id
(
wilber
)
print
wilber
print
[
id
(
ele
)
for
ele
in
wilber
]
will
[
0
]
=
"Wilber"
will
[
2
]
.
append
(
"CSS"
)
print
id
(
will
)
print
will
print
[
id
(
ele
)
for
ele
in
will
]
print
id
(
wilber
)
print
wilber
print
[
id
(
ele
)
for
ele
in
wilber
]
|
代码结果为:
分析一下这段代码:
浅拷贝会创建一个新的对象,这个例子中”wilber is not will”
但是,对于对象中的元素,浅拷贝就只会使用原始元素的引用(内存地址),也就是说”wilber[i] is will[i]”
由于list的第一个元素是不可变类型,所以will对应的list的第一个元素会使用一个新的对象39758496
但是list的第三个元素(列表)是一个可变类型,修改操作不会产生新的对象,所以will的修改结果会相应的反应到wilber上
总结一下,当我们使用下面的操作的时候,会产生浅拷贝的效果:
深拷贝
最后来看看深拷贝:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
|
import
copy
will
=
[
"Will"
,
28
,
[
"Python"
,
"C#"
,
"JavaScript"
]
]
wilber
=
copy
.
deepcopy
(
will
)
print
id
(
will
)
print
will
print
[
id
(
ele
)
for
ele
in
will
]
print
id
(
wilber
)
print
wilber
print
[
id
(
ele
)
for
ele
in
wilber
]
will
[
0
]
=
"Wilber"
will
[
2
]
.
append
(
"CSS"
)
print
id
(
will
)
print
will
print
[
id
(
ele
)
for
ele
in
will
]
print
id
(
wilber
)
print
wilber
print
[
id
(
ele
)
for
ele
in
wilber
]
|
代码的结果为:
分析一下这段代码:
跟浅拷贝类似,深拷贝也会创建一个新的对象,这个例子中”wilber is not will”
但是,对于对象中的元素,深拷贝都会重新生成一份(有特殊情况,下面会说明),而不是简单的使用原始元素的引用(内存地址)
例子中will的第三个元素指向39737304,而wilber的第三个元素是一个全新的对象39773088,也就是说,”wilber[2] is not will[2]”
由于list的第一个元素是不可变类型,所以will对应的list的第一个元素会使用一个新的对象39758496
但是list的第三个元素是一个可变类型,修改操作不会产生新的对象,但是由于”wilber[2] is not will[2]”,所以will的修改不会影响wilber
拷贝的特殊情况
其实,对于拷贝有一些特殊情况:
也就是说,对于这些类型,”obj is copy.copy(obj)” 、”obj is copy.deepcopy(obj)”
总结
本文介绍了对象的赋值和拷贝,以及它们之间的差异: