Python中的对象之间赋值时是按引用传递的,如果需要拷贝对象,需要使用标准库中的copy模块。
1. copy.copy 浅拷贝 只拷贝父对象,不会拷贝对象的内部的子对象。
2. copy.deepcopy 深拷贝 拷贝对象及其子对象
一个很好的例子:
import
copy
a
=
[
1
,
2
,
3
,
4
, [
'
a
'
,
'
b
'
]]
#
原始对象
b
=
a
#
赋值,传对象的引用
c
=
copy.copy(a)
#
对象拷贝,浅拷贝
d
=
copy.deepcopy(a)
#
对象拷贝,深拷贝
a.append(
5
)
#
修改对象a
a[
4
].append(
'
c
'
)
#
修改对象a中的['a', 'b']数组对象
print
'
a =
'
, a
print
'
b =
'
, b
print
'
c =
'
, c
print
'
d =
'
, d
输出结果:
a = [1, 2, 3, 4, ['a', 'b', 'c'], 5]
b = [1, 2, 3, 4, ['a', 'b', 'c'], 5]
c = [1, 2, 3, 4, ['a', 'b', 'c']]
d = [1, 2, 3, 4, ['a', 'b']]
1. copy.copy 浅拷贝 只拷贝父对象,不会拷贝对象的内部的子对象。
2. copy.deepcopy 深拷贝 拷贝对象及其子对象
一个很好的例子:
![](https://www.cnblogs.com/Images/OutliningIndicators/None.gif)
![](https://www.cnblogs.com/Images/OutliningIndicators/None.gif)
![](https://www.cnblogs.com/Images/OutliningIndicators/None.gif)
![](https://www.cnblogs.com/Images/OutliningIndicators/None.gif)
![](https://www.cnblogs.com/Images/OutliningIndicators/None.gif)
![](https://www.cnblogs.com/Images/OutliningIndicators/None.gif)
![](https://www.cnblogs.com/Images/OutliningIndicators/None.gif)
![](https://www.cnblogs.com/Images/OutliningIndicators/None.gif)
![](https://www.cnblogs.com/Images/OutliningIndicators/None.gif)
![](https://www.cnblogs.com/Images/OutliningIndicators/None.gif)
![](https://www.cnblogs.com/Images/OutliningIndicators/None.gif)
![](https://www.cnblogs.com/Images/OutliningIndicators/None.gif)
![](https://www.cnblogs.com/Images/OutliningIndicators/None.gif)
![](https://www.cnblogs.com/Images/OutliningIndicators/None.gif)
输出结果:
a = [1, 2, 3, 4, ['a', 'b', 'c'], 5]
b = [1, 2, 3, 4, ['a', 'b', 'c'], 5]
c = [1, 2, 3, 4, ['a', 'b', 'c']]
d = [1, 2, 3, 4, ['a', 'b']]
Python 天天美味系列(总)
Python 天天美味(20) - 命令行参数sys.argv
Python 天天美味(21) - httplib,smtplib
Python 天天美味(22) - 拷贝对象(深拷贝deepcopy与浅拷贝copy)
Python 天天美味(23) - enumerate遍历数组
...
本文转自CoderZh博客园博客,原文链接:http://www.cnblogs.com/coderzh/archive/2008/05/17/1201506.html,如需转载请自行联系原作者