Python: Deep copy objects using copy module

Source: Internet
Author: User
Tags shallow copy

The Python language has deep copy and shallow copy concepts, what is deep copy, shallow copy?

Shallow copy (shallow copy): Constructs a new composite object and inserts it into the object from the reference found in the original object (that is, the address, not the content pointed to by the address) . There are many ways to implement a shallow copy, such as factory functions, slicing operations, and copy operations in the Copy module.

Deep copy: Also constructs a new compound object, but encounters a reference that continues to recursively copy the content it points to, meaning that he continues to perform copies of the object pointed to by the reference, so that the resulting object is not affected by other object operations. The implementation of a deep copy relies on the deepcopy () operation of the copy module

Let's take a look at the following example, define a pizza class and order class, and react to pizza information and order information, respectively.

#coding =utf-8import copyclass pizza (object):     "" "     Pizza class      ""     def __init__ (Self,name,size,price):         self.name = name         self.size = size        self.price = price     def showpizzainfo (self):        print  "". Join (' pizza name: ', self.name) '           print  '. Join (("Pizza size:", str (self.size)))         print  "". Join (' Pizza price: ', str (self.price))          #字符串的拼接尽量使用join () function, do not use the + sign , because the former is more efficient and more pythonnic    def getpizzainfo (self):         return&Nbsp;self.name,self.size,self.price    def changename (Self,name):         self.name = name    def changesize (Self,size) :        self.size = size    def  Changeprice (self,price):         self.price = priceclass  order (object):     "" "     Order Class     " "     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&nbsP;changename (self,name):         self.customername = name     def getorderdetail (self):         print   "". Join (' customer name: ', self.customername)         for  one in self.pizzalist:             One.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 infomation: " Customer1.getorderdetail () print  "--------------------"

The above code describes the scenario where the customer 1 placed an order and printed out the specific order. The results of the operation are as follows:

Customer1 Order Infomation:

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

--------------------

Suppose the customer 2 also want to with the customer 1 under the same order, only changed the size of fruit pizza, then the price should be modified accordingly. Then think of copying the customer 1 of the order information and make certain changes, the code is as follows:

Customer2 = copy.copy (customer1) print "". Join (["Order2 Customer Name:", Customer2.customername]) customer2.changename ("Li") Customer2.getpizza (2). Changesize (9) Customer2.getpizza (2). Changeprice (p) print "Customer2 Order information: "Customer2.getorderdetail () print"----------------------"

The output results are as follows:

Order2 Customer Name:zhang

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

Can say or meet the requirements of customers 2, modify the customer 2 order information and then to see the customer 1 order information,

Print "Customer1 order infomation:" Customer1.getorderdetail () print "----------------------"

The results are as follows:

Customer1 Order Infomation:

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:9

Pizza price:30

----------------------

Customer 1 Order information in addition to the customer name, the other and the customer 2 order information is actually the same. If this is really a generated system, will certainly affect customer satisfaction, because customer 1 did not ask to modify the order information ah. What's going on here?

The pizzalist in Customer1 is a list of pizza objects, which are actually references to a specific pizza object, which in memory is a specific location that can print out their IDs

Print ID (customer1.pizzalist[0]) Print ID (customer1.pizzalist[1]) Print ID (customer1.pizzalist[2]) Print ID ( Customer1.pizzalist)

The results are as follows:

140206506600080

140206506602064

140206506652560

140206507110552

Customer2 order is obtained by copy.copy (Customer1), the Customer2 pizzalist ID printed out with customer1 of pizzalist at the same time printed out, the code is as follows:

Print ID (customer1.pizzalist[0]) Print ID (customer1.pizzalist[1]) Print ID (customer1.pizzalist[2]) Print ID ( customer1.pizzalist) print "--------------------------" Print ID (customer2.pizzalist[0]) Print ID ( CUSTOMER2.PIZZALIST[1]) Print ID (customer2.pizzalist[2]) Print ID (customer2.pizzalist)

Printing results are as follows

140206506600080

140206506602064

140206506652560

140206507110552

--------------------------

140206506600080

140206506602064

140206506652560

140206507110552

The discovery is the same, because Copy.copy () obtains a shallow copy, which simply copies the address of the object and does not copy the specific content referred to in the corresponding address.

In a data structure that contains references, shallow copies cannot be completely copied, and when a mutable object such as a dictionary or list is present, it simply copies its reference address and does not copy the contents of the corresponding address. To solve this problem, a deep copy is required, and the deep copy not only copies the reference but also copies the object that the reference points to (that is, the content), so the objects that are deeply copied are independent of the original object.

This problem does not occur if the above program is changed to Customer2 = Copy.deepcopy (customer1).

Here is a brief introduction to some of the copy module's knowledge:

The primary external interface of the Copy module is copy () and Deepcopy ().

 #coding =utf-8import copyclass copyobj (object):     def __repr__ (self):        return  "COPYOBJ"     def __copy__ (self):        return  " Copy "Obj = copyobj () obj1 = copy.copy (obj) obj2 = copy.deepcopy (obj) print  objprint obj1print obj2print  "-----------------" Class copyobj (object):     def __repr__ (self):        return  "Copyobj"      def __deepcopy__ (self,meno=none):         return   "Deep copy" A = copyobj () b = copy.copy (a) c = copy.deepcopy (a) print  aprint bprint c 

The output results are as follows:

Copyobj

Copy

Copyobj

-----------------

Copyobj

Copyobj

Deep copy


Python: Deep copy objects using copy module

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.