Object copy in python sample python reference pass

  • 2020-04-02 13:21:31
  • OfStack

What is reference passing? Let's look at a C++ function that swaps two Numbers:


void swap(int &a, int &b)
{
    int temp;
    temp = a;
    a = b;
    b = temp;
}

This example is an example of passing by reference! The purpose is to illustrate the concept: reference-passing means that you are passing a reference to an object, and changes to that reference also cause changes to the original object. Those of you who have learned C/C++ know that when you swap two Numbers, if you implement a swap function yourself, you need to pass a reference or pointer to it.

Python directly USES the reference to pass, how convenient, you also want to make fun of? Did it ever occur to you that I didn't want to change my partner's situation? If so, look here!

Suppose I now have a list called l1, and I now need a copy of l1. If I directly use a method such as l2 = l1, and then I make a series of modifications to l2, it will be equivalent to me directly making modifications to l1, which is not what I want! Such as:


l1 = [1, 2]
l2 = l1
l2.append(3)
print l1
print l2
# l1 = [1, 2, 3], l2 = [1, 2, 3]

This is the result of Python reference passing, which means that l1 and l2 belong to the same list object, so how do you get a different one? It's so easy to slice and sprinkle.


l1 = [1, 2]
l2 = l1[:]
l2.append(3)
# l1 = [1, 2], l2 = [1, 2, 3]

Yeah, that's it. No, no. Are you sure this is gonna work? Let's look at a more complicated situation:


l1 = [[1, 2], 3]
l2 = l1[:]
l2.append(4)
# l1 = [[1, 2], 3], l2 = [[1, 2], 3, 4]
l2[0].append(5)
# l1 = [[1, 2, 5], 3], l2 = [[1, 2, 5], 3, 4]

Aha, something seems to be wrong ha, this is not what we need! What to do? Okay, let's get to the main topic of the day, the copy module in Python!


import copy

If you want to copy a container object and all the elements in it (including the children of the elements), use copy.deepcopy. This method takes some time and space, but it's the only way to do it if you want a full copy. The way we sliced up above is equivalent to the copy function in the copy module.

The operation copied above becomes so easy:


l1 = [[1, 2], 3]
l2 = copy.copy(l1)
l3 = copy.deepcopy(l1)
l2.append(4)
l2[0].append(5)
l3[0].append(6)
# l1 = [[1, 2, 5], 3], l2 = [[1, 2, 5], 3, 4], l3 = [[1, 2, 6], 3]

Related notes:


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.


Related articles: