现在的位置: 首页 > 综合 > 正文

004_001 Python 对象拷贝

2017年12月10日 ⁄ 综合 ⁄ 共 695字 ⁄ 字号 评论关闭

代码如下:

#encoding=utf-8

print '中国'

#对象拷贝 python的赋值和参数传递以及结果返回一般都是原对象的引用

import copy

print '----引用'
lista=[1,2,3]
listb=lista
listb.append(4)

print listb
print lista

#拷贝
print '----拷贝'
lista=[1,2,3]
listb = copy.copy(lista)
listb.append(4)
print listb
print lista

#拷贝
print '----深入拷贝'
lista=[1,2,3]
listb=[1,2,3,lista]
listc = copy.copy(listb)  #浅拷贝  影响原来的对象
listc[3].append(4)
print listc
print lista

lista=[1,2,3]
listb=[1,2,3,lista]
listc = copy.deepcopy(listb) #深拷贝 不影响原来的对象
listc[3].append(4)
print listc
print lista

# is是相同 ==是相等
print '----is 和 == '
s='cat'
t=copy.copy(s) #还是原来的对象
q=s

print s == t
print s == q

print s is t
print s is q

打印结果如下:

中国
----引用
[1, 2, 3, 4]
[1, 2, 3, 4]
----拷贝
[1, 2, 3, 4]
[1, 2, 3]
----深入拷贝
[1, 2, 3, [1, 2, 3, 4]]
[1, 2, 3, 4]
[1, 2, 3, [1, 2, 3, 4]]
[1, 2, 3]
----is 和 == 
True
True
True
True

抱歉!评论已关闭.