需求,当有一个实例a,我们需要一个新的实例b,b同a拥有相同的属性。
当我们使用a=b的模式的时候是一个赋值的过程。a和b指向同一个实例。b的任何操作都同a一样。
在这个使用需要使用copy模块。根据a copy出一个一模一样的b。
class shelf(object): def __init__(self): self.books = [] def addbook(self, bookname): self.books.append(bookname) def delbook(self, bookname): self.books.remove(bookname) def showbook(self): for book in self.books: print book shelf1 = shelf() shelf1.addbook("the great gatsby") shelf1.addbook("the little prince") shelf1.showbook() print str(id(shelf1)) print "------------0--------------" import copy shelf2 = copy.copy(shelf1) shelf2.showbook() print str(id(shelf2)) print "------------1---------------"
结果:
the great gatsby the little prince 31398768 ------------0-------------- the great gatsby the little prince 40185472 ------------1---------------
可以看出shelf1和shelf2是两个实例,但是有着相同的属性。
但是有一个问题:
shelf2.delbook("the little prince") shelf2.showbook() print "-------------2--------------" shelf1.showbook()
结果呢?
the great gatsby -------------2-------------- the great gatsby
这说明虽然shelf1和shelf2不同的类,但是内容仍然指向相同的地点。
如何解决这个问题:
copy.deepcopy
看代码:
shelf3 = copy.deepcopy(shelf1) print "------------3---------------" shelf3.showbook() shelf3.addbook("The Wonderful Wizard of Oz") print "-------------4--------------" shelf3.showbook() print "--------------5-------------" shelf1.showbook()
结果:
the great gatsby -------------4-------------- the great gatsby The Wonderful Wizard of Oz --------------5------------- the great gatsby
这样就解决了内容指向相同的问题。
所以copy模块中copy函数和deepcopy函数的区别就是当类内部有list,dict时候,copy产生的实例有着指向相同内容,deepcopy则将list/dict也创建一个备份。
完整代码:
# -*- coding: utf-8 -*- class shelf(object): def __init__(self): self.books = [] def addbook(self, bookname): self.books.append(bookname) def delbook(self, bookname): self.books.remove(bookname) def showbook(self): for book in self.books: print book shelf1 = shelf() shelf1.addbook("the great gatsby") shelf1.addbook("the little prince") shelf1.showbook() print str(id(shelf1)) print "------------0--------------" import copy shelf2 = copy.copy(shelf1) shelf2.showbook() print str(id(shelf2)) print "------------1---------------" shelf2.delbook("the little prince") shelf2.showbook() print "-------------2--------------" shelf1.showbook() shelf3 = copy.deepcopy(shelf1) print "------------3---------------" shelf3.showbook() shelf3.addbook("The Wonderful Wizard of Oz") print "-------------4--------------" shelf3.showbook() print "--------------5-------------" shelf1.showbook()