For example, distinguish between shallow replication and deep replication in Python
This article mainly introduces how to distinguish between shallow replication and deep replication in Python. It is an important knowledge in getting started with Python. For more information, see
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.
?
1 2 3 4 5 6 7 8 9 10 11 12 13 14 |
# Coding = gbk Import copy L1 = [1, 2, [3, 4] L2 = copy. copy (l1) Print l1 Print l2 L2 [2] [0] = 50 Print l1 Print 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:
?
1 2 3 4 5 6 7 8 9 10 11 12 13 |
Import copy L1 = [1, 2, [3, 4] L2 = copy. deepcopy (l1) Print l1 Print l2 L2 [2] [0] = 50 Print l1 Print 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:
?
1 2 3 4 5 6 7 8 9 10 11 12 13 |
Class CopyObj (object ): Def _ repr _ (self ): Return "CopyObj" Def _ copy _ (self ): Return "Hello" Obj = CopyObj () Obj1 = copy. copy (obj) Print obj Print obj1 # ---- Result ---- CopyObj Hello |