For example, distinguish between shallow replication and deep replication in Python

Source: Internet
Author: User

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

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.