标签:拷贝 port style rip 对象 pre 容器类 列表 epc
首先我们来看下面一段代码:
1 1 >>> names = ["maqing"," peilin"," xiaoming"," lilei"," hanmeimei",["maqing","wangchuan","lilong"]] 2 2 >>> names2 = names.copy() 3 3 >>> print(names) 4 4 [‘maqing‘, ‘ peilin‘, ‘ xiaoming‘, ‘ lilei‘, ‘ hanmeimei‘, [‘maqing‘, ‘wangchuan‘, ‘lilong‘]] 5 5 >>> names[2] = "小明" 6 7 >>> print(names) 7 8 [‘maqing‘, ‘ peilin‘, ‘小明‘, ‘ lilei‘, ‘ hanmeimei‘, [‘maqing‘, ‘wangchuan‘, ‘lilong‘]] 8 9 >>> print(names2) 9 10 [‘maqing‘, ‘ peilin‘, ‘ xiaoming‘, ‘ lilei‘, ‘ hanmeimei‘, [‘maqing‘, ‘wangchuan‘, ‘lilong‘]] 10 11 >>> names[-1][2] = "李龙" 11 12 >>> print(names) 12 13 [‘maqing‘, ‘ peilin‘, ‘小明‘, ‘ lilei‘, ‘ hanmeimei‘, [‘maqing‘, ‘wangchuan‘, ‘李龙‘]] 13 14 >>> print(names2) 14 15 [‘maqing‘, ‘ peilin‘, ‘ xiaoming‘, ‘ lilei‘, ‘ hanmeimei‘, [‘maqing‘, ‘wangchuan‘, ‘李龙‘]]
第一步:修改names中‘xiaoming‘的值为中文"小明",输出列表发现只有names中修改了,但names2中没有修改,符合copy的性质。
第二步:修改names中二级列表"lilong"的值为"李龙",输出names和names2,我们发现‘lilong‘的值都改为中文了,貌似这不符合copy的性质。
浅copy的方法有三种:
1 person = [‘name‘,[‘saving‘,100]] 2 p1 = copy.copy(person) 3 p2 = person[:] 4 p3 = list(person)
1 >>> import copy 2 >>> names = ["Will", 28, ["Python", "C#", "JavaScript"]] 3 >>> names2 = copy.deepcopy(names) 4 >>> names[1] = ‘27‘ 5 >>> print(names) 6 [‘Will‘, ‘27‘, [‘Python‘, ‘C#‘, ‘JavaScript‘]] 7 >>> print(names2) 8 [‘Will‘, 28, [‘Python‘, ‘C#‘, ‘JavaScript‘]] 9 >>> names[2][1] = "Ruby" 10 >>> print(names) 11 [‘Will‘, ‘27‘, [‘Python‘, ‘Ruby‘, ‘JavaScript‘]] 12 >>> print(names2) 13 [‘Will‘, 28, [‘Python‘, ‘C#‘, ‘JavaScript‘]]
总结
本文介绍了对象的赋值和拷贝,以及它们之间的差异:
Day2-Python基础2---浅copy、深copy的差别
标签:拷贝 port style rip 对象 pre 容器类 列表 epc
原文地址:http://www.cnblogs.com/bldly1989/p/6530650.html