首先,我们知道Python3中,有6个标准的数据类型,他们又分为可变和不可变。
不可变:Number(数字)、String(字符串)、Tuple(元组)。
可以变:List(列表)、Dictionary(字典)、Set(集合)。
copy模块里面的copy方法实现。
浅拷贝后,改变原始对象中为可变类型的元素的值,会同时影响拷贝对象;改变原始对象中为不可变类型的元素的值,不会响拷贝对象。
代码演示
import copy class Father(object): def __init__(self, age): self.age = age; #定义共有属性 age = 44; name= ['feige','666']; #私有方法访问共有属性 def printName(self): print('the name of father is:'+self.name); #共有方法访问私有属性! def printAge(self): print('the age of father is :'+str(self.age)); #进行浅拷贝 f1 = Father(24); f2 = copy.copy(f1); #测试两个爹地址是否相同 print(id(f1)); print(id(f2)); #结果 58195728 58785040 #测试两个爹年龄地址是否相同 print(id(f1.age)); print(id(f2.age)); #结果 1392272848 1392272848 #测试两个爹名字地址是否相同 print(id(f1.name)); print(id(f2.name)); #结果 1392272848 1392272848 #改变爹1年龄,爹2不会改变。 f1.age = 66; print(f2.age); #结果:24 #因为name地址相同,且是可变对象,所以,爹2改名字了,爹1也会改变。 f1.name[0] = 'Niu Bi'; print(f2.name); #结果 ['Niu Bi', '666'] copy模块里面的deepcopy方法实现。
深拷贝,除了顶层拷贝,还对子元素也进行了拷贝。
经过深拷贝后,原始对象和拷贝对象所有的元素地址都没有相同的了。
代码演示
import copy class Father(object): def __init__(self, age): self.age = age; #定义共有属性 age = 44; name= ['feige','666']; #私有方法访问共有属性 def printName(self): print('the name of father is:'+self.name); #共有方法访问私有属性! def printAge(self): print('the age of father is :'+str(self.age)); #进行浅拷贝 f1 = Father(24); f2 = copy.deepcopy(f1); #测试两个爹地址是否相同 print(id(f1)); print(id(f2)); #结果 45416208 51642064 #测试两个爹年龄地址是否相同 print(id(f1.age)); print(id(f2.age)); #结果 1392272848 1392272848