Python object replication, deep replication, and shallow Replication

Source: Internet
Author: User

You want to copy an object, because in Python, whether you pass an object as a parameter or as a function return value, it is passed by reference.

Discussion:

The copy module in the Standard Library provides two methods for copying. One method is copy, which returns objects with the same content as parameters.

Import copy
New_list = Copy. Copy (existing_list)

In some cases, you can use the deepcopy method to copy the attributes of an object:

Import copy
New_list_of_dicts = copy. deepcopy (existing_list_of_dicts)

When you assign values to an object (transmitted as a parameter or returned value), Python and Java always pass reference of the original object, rather than a copy. some other languages always transmit copies when assigning values. python never guesses user requirements. If you want a copy, you must explicitly ask.
Python behavior is simple, fast, and consistent. However, if you need to copy an object but it is not explicitly written, problems will occur, such:

>>> A = [1, 2, 3] >>> B = A >>> B. append (5) >>> Print A, B [1, 2, 3, 5] [1, 2, 3, 5]
Here, both variables A and B point to the same object (a list). Therefore, once you modify either of them, the other one will also be affected. in any case, the original object will be modified.
Note:
To become a python expert, the first thing to note is the change operation and assignment of objects, which are all reference operations on objects. A statement such as a = [] re-binds a to a new object, but does not affect the previous object. however, object replication is different. After object replication, object change operations are different.
If you want to modify an object without affecting the original object, you need to copy the object. as described in this section, you can use the two methods in the copy module to implement the requirements. generally, you can use copy. copy, which can be used for shallow copy of objects. It copies objects, but still uses references for elements in objects.
In light replication, you sometimes cannot get a copy that is exactly the same as the original object. If you want to modify the elements in an object, not just the object itself:

>>> List_of_lists = [['a'], [1, 2], ['Z', 23]
>>> Copy_lol = Copy. Copy (lists_of_lists)
>>> Copy_lol [1]. append ('boo ')
>>> Print list_of_lists, copy_lol
[['A'], [1, 2, 'boo'], ['Z', 23] [['a'], [1, 2, 'boo'], ['Z', 23]

Here, the variables list_of_lists and copy_lol point to two different objects, so we can modify either of them without affecting the other. however, if we modify the elements in an object, the other will also be affected, because the elements in them are still shared references.
If you want to copy a container object and all its elements (including its child elements), use copy. deepcopy, this method consumes some time and space. However, if you need to completely copy, this is the only method.
For general shortest copies, use copy. copy. Of course, you need to understand the object you want to copy. to copy the list l, use List (L), copy a dictionary D, use dict (D), copy a set S, and use set (s). In this way, we have concluded a rule. If you want to copy an object o, which belongs to the built-in type T, you can use t (o) to obtain a copy. dict also provides a copy version, dict. copy, which is the same as dict (d). I recommend you use the latter, which makesCodeMore consistent, and a few characters less.
To copy another type, whether it is written by yourself or in the database, use copy. copy: if you write a class by yourself, there is no need to bother writing clone and copy functions. If you want to define your own class replication method, implement a _ copy __, or _ getstate _ and _ setstate __. if you want to define your own type of deepcopy, implement method _ deepcopy __.
Note that you do not need to copy unmodifiable objects (string, number, and tuples), because you do not have to worry about modifying them. if you want to copy it, you will still get the original one. although it is harmless, it is a waste of effort:

>>> S = 'cat'
>>> T = Copy. Copy (s)
>>> S is t
True

The is operator is used to determine not only whether two objects are completely consistent, but also the same object (is judgment identifier, to compare content, use = ), determining whether the identifiers are equal makes no sense to the objects that cannot be modified. however, identifying identifiers is sometimes important for modifiable objects. For example, if you are not sure whether a and B point to the same object, using a is B will immediately get the result. in this way, you can determine whether to use object copy.
Note:
You can use another copy method to specify a list l, which can be a complete slice L [:] or a list resolution [X for X in L, try L + [], L * 1... however, the above two methods will be confusing, and the use of list (l) is the clearest and fastest. Of course, due to historical reasons, you may often see the L [:] method.
For dict, you may have seen the following replication method:
>>> For somekey in D:
... D1 [somekey] = d [somekey]

Or a simpler method, D1 ={}, d1.update (d). In any case, the code is inefficient. Use d1 = dict (d.

Instructions:

Copy (X)
Shallow copy operation on arbitrary Python objects.

See the module's _ Doc _ string for more info.

Deepcopy (x, memo = none, _ nil = [])
Deep copy operation on arbitrary Python objects.

See the module's _ Doc _ string for more info.

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.