Python variable-depth understanding of the object / immutable transmission involved in replication, depth (shallow) copy

In-depth understanding of the object python

Python uses the object model to store data, so in python everything is an object .

  • Object has three properties:
    • Identity mark: be unique, it can be understood as an object memory address. id ()
    • Type: of the type ()
    • value

So, any variable can be used id () and type () to view the object's properties 

  • The value of an object is read-only or can be updated, the object (i.e. all data types python) into a variable type (the mutable) and immutable (the immutable) .
    • Immutable type: All numeric type, a string, a tuple
    • Variable types: lists, dictionaries.
str = "abc"
str[0] = "d"

"""
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: 'str' object does not support item assignment
"""

tuple = (2,3)
tuple[0] = 4
"""
Traceback (most recent call last)
  File "<stdin>", line 1, in <module>
TypeError: 'tuple' object does not support item assignment
"""


复制代码

Note: Some of python operation of immutable objects, and appears to be changed, in fact, generate a new object.

str = "abc"
print(id(str)) # 4483428440

str = str + "d"
print(str,id(str)) # ('abcd', 4515702032)

str = str.replace("a","d")
print(str,id(str)) # ('dbcd', 4778928816)
复制代码

python assignment and mass participation

  • Assignment of variables, so that only that variable points to an object, not to make variable points to a memory address, nor a copy of the object to the variable.

"Remember that arguments are passed by assignment in Python"

  • On parameter passing, precisely, python that is passed in the parameter assignment transfer (passed by the Assignment) . python all data types are objects, parameters are passed, only that the new variable with the original variables point to the same object of it , there is no transfer value is passed or drinking a say.

For python, whether it is an assignment or mass participation, not point to a specific memory address, but point to a specific object.

  • If the object is variable, and that when it changes, it all points to the variable will change

  • If the object is immutable, all variables that point to the value of the object is always the same, if by operating the "Update" immutable objects, in essence, is not updated, it is to generate a new object.

def my_func1(b):
    print("b:id_1:{}".format(id(b)))
    b = 2
    print("b:id_2:{}".format(id(b)))
    
a = 1
print("a:id_1:{}".format(id(a)))
my_func1(a)
print("a:{}".format(a))
print("a:id_2:{}".format(id(a)))

#a:id_1:140553278747896
#b:id_1:140553278747896
#b:id_2:140553278747872
#a:1
#a:id_2:140553278747896

复制代码
def my_func2(list_b):
    print("list_b:id_1:{}".format(id(list_b)))
    list_b.append(4)
    print("list_b:id_2:{}".format(id(list_b)))

#list_a = [1, 2, 3]
#print("list_a:id_1:{}".format(id(list_a)))
#my_func2(list_a)
#print(list_a)
#print("list_a:id_2:{}".format(id(list_a)))
复制代码

Deep copy (deep copy) and shallow copy (shallow copy)

We already know, assignment and mass participation is the essence of the original variable to point to an object, that in python, if you want to generate a new object, it would need to copy (copy). Deep and shallow copy copy will create a new object, rather than the original object reference itself.

  • Shallow copy new object is created, a reference to the first layer of the object the original object.
    • Shallow copy of three forms: a slice operation, plant function, copy function copy module.

      a = [1,2,3]
      slicing operation: b = a [:] or b = [xforxina];
      plant functions: List B = (A);
      Copy function: b = copy.copy (a);

    • Shallow copy generated list list_b not a list list_a, the judge may find that they use is not the same object, use the id to view, they do not point to the same piece of memory space. In this case, the list list_a and list_b are different objects, modify the list list_b theoretically not affect the list list_a.

    • But note that the shallow copy is called a shallow copy, it is only just copy the layer. But when we see its address elements, you can see the address contains elements of both are the same. We modified the nested list, modify the outer element, it will modify its reference, so that they point to a different location, modify elements nested list, address list has not changed, are pointing to a location with

import copy
list_a = [[a,2],{"a":2}]
print("list_a'id:{}".format(id(list_a)))  # list_a'id:4780111992
for a in list_a:
    print("a'id:{}".format(id(a)))          # a'id:4779267928
                                            # a'id:4780054520

list_b = list_a[:]
print("list_b'id:{}".format(id(list_b)))  #list_b'id:4779229336
for b in list_b:
    print("b'id:{}".format(id(b)))         # b'id:4779267928
                                           # b'id:4780054520

list_a.append(3)
print(list_b)           # [[{'a': 2}, 2], {'a': 2}]
    
list_a[0].append(4)
print(list_b)           # [[{'a': 2}, 2, 4], {'a': 2}]

复制代码
  • Deep copy (deep copy)
    • Only one form deep copy, copy module DeepCopy () function. Deep copy and copy the corresponding shallow, deep copy of the copied object all the elements, including multiple nested elements. So, it's time and space overhead is higher.

    • The same list list_a, if used list_b = copy.deepcopy (list_a), then modify the list to the list will not affect list_b list_a, nested lists with even deeper level, it will not have any effect, because the deep copy copy out of the object it is simply a brand new object, no longer have any association with the original object.

import copy
list_a = [[a,2],{"a":2}]
print("list_a'id:{}".format(id(list_a)))  # list_a'id:4775350000
for a in list_a:
    print("a'id:{}".format(id(a)))      # a'id:4781058888
                                        # a'id:4780657472

list_b = copy.deepcopy(list_a)
print("list_b'id:{}".format(id(list_b)))  # list_b'id:4780511384
for b in list_b:
    print("b'id:{}".format(id(b)))      #b'id:4775453616
                                        #b'id:4775426600


list_a.append(3)    
print(list_b)           [[{'a': 2}, 2], {'a': 2}]
    
list_a[0].append(3)
print(list_b)           [[{'a': 2}, 2], {'a': 2}]
    
复制代码
  • Note: Whether deep copy or a shallow copy, for variable types, for all of numbers, characters, tuples, these immutable types, not a copy of that variable is referenced produce the original object. If a tuple of variable values ​​atoms containing type object, even if a deep copy, only to give a pale copy.
import copy
# s = "aa"
# s = 123
s = (2,3,4)
print(id(s))  # 4774929104
v = copy.copy(s)
print(id(v))  # 4774929104
复制代码

Reproduced in: https: //juejin.im/post/5d078309f265da1bbf691dfa

Guess you like

Origin blog.csdn.net/weixin_34206899/article/details/93181734