浅拷贝就是对引用的拷贝,只拷贝父对象,里面的数据不拷贝出来,其中的数据与原对象里面数据用的是相同的地址空间(新开辟了一个内存空间)
深拷贝就是对对象的资源的拷贝,拷贝父对象以及里面的子对象。深拷贝把原对象独立开来,有自己的存储空间,有自己定义的数据,跟原对象一点关系也没有。(开辟大空间同时开辟大空间中的小空间放子对象)
python中,深拷贝和浅拷贝仅仅是在内存当中对数据的一个应用,在实际开发时,可以考虑这样的数据处理方式对程序速率的影响。
import copy
class Pizza(object):
def __init__(self,name,size,price):
self.name = name
self.size = size
self.price = price
def getPizzaInfo(self):
return self.name,self.size,self.price
def showPizzaInfo(self):
print('Pizza name: ', self.name)
print('Pizza size: ', self.size)
print('Pizza price: ', self.price)
def changeSize(self,size):
self.size = size
def changePrice(self,price):
self.price = price
class Order(object):
def __init__(self,name):
self.customername = name
self.pizzaList = []
self.pizzaList.append(Pizza('mushroom',12,30))
def ordermore(self,pizza):
self.pizzaList.append(pizza)
def changeName(self,name):
self.customername = name
def getorderdetail(self):
print('customer name: ', self.customername)
for i in self.pizzaList:
i.showPizzaInfo()
def getPizza(self,number):
return self.pizzaList[number]
customer1 = Order('zhang')
customer1.ordermore(Pizza('seafood',9,40))
customer1.ordermore(Pizza('fruit',12,35))
print('customer1 order information:')
customer1.getorderdetail()
print('-----------------------')
# 深拷贝
customer2 = copy.deepcopy(customer1)
customer2.changeName('li')
print('order 2 customer name: ', customer2.customername)
customer2.getPizza(2).changeSize(9)
customer2.getPizza(2).changePrice(30)
print('customer2 order information:')
customer2.getorderdetail()
结果:
customer1 order information:
customer name: zhang
Pizza name: mushroom
Pizza size: 12
Pizza price: 30
Pizza name: seafood
Pizza size: 9
Pizza price: 40
Pizza name: fruit
Pizza size: 12
Pizza price: 35
-----------------------
order 2 customer name: li
customer2 order information:
customer name: li
Pizza name: mushroom
Pizza size: 12
Pizza price: 30
Pizza name: seafood
Pizza size: 9
Pizza price: 40
Pizza name: fruit
Pizza size: 9
Pizza price: 30
如果改成浅拷贝:
customer2 = copy.copy(customer1)
,那么对customer2的订单信息修改后,customer1的订单信息会变得跟customer2的一样。
这是因为:
通过copy.copy()得到的customer2是customer1的浅拷贝,仅仅拷贝了pizzalist里面对象的地址而不对对应地址所指向的具体内容(即具体的pizza)进行拷贝,因此customer2中的pizzalist所指向的具体内容是和customer1中一样的。
网友评论