For example, distinguish between shallow replication and deep replication in Python, and for example, distinguish between python
The copy module is used to copy objects. This module is very simple and only provides two main methods: copy. copy and copy. deepcopy, which respectively represent the shortest copy and deep copy. What is light replication, what is deep replication, and information about a truck and a truck on the Internet is not described here. The copy operation is only valid for composite objects. The two methods are described in a simple example.
The shortest copy only copies the object itself, but does not copy the object referenced by the object.
# Coding = gbkimport copyl1 = [1, 2, [3, 4] l2 = copy. copy (l1) print l1print l2l2 [2] [0] = 50 print l1print l2 # ---- result ---- [1, 2, [3, 4] [1, 2, [3, 4] [1, 2, [50, 4] [1, 2, [50, 4]
For the same code, if deep replication is used, the results are different:
Import copyl1 = [1, 2, [3, 4] l2 = copy. deepcopy (l1) print l1print l2l2 [2] [0] = 50 print l1print l2 # ---- result ---- [1, 2, [3, 4] [1, 2, [3, 4] [1, 2, [3, 4] [1, 2, [50, 4]
Change the default copy Behavior
When defining a class, you can change the default behavior of copy by defining the _ copy _ and _ deepcopy _ methods. The following is a simple example:
Class CopyObj (object): def _ repr _ (self): return "CopyObj" def _ copy _ (self): return "Hello" obj = CopyObj () obj1 = copy. copy (obj) print objprint obj1 # ---- result ---- CopyObjHello