Assignment in Python, deep copy and shallow copy (memory address)
1, the python with the variable object immutable objects
(1) variable object: dict, list
def dict_test(): a = {} b = a print(id(a)) # 140367329543360 a['a'] = 'hhhh' print('id a:' + str(id(a))) # id a:140367329543360 print('a:' + str(a)) # a:{'a': 'hhhh'} print('id b:' + str(id(b))) # id b:140367329543360 print('b:' + str(b)) # b:{'a': 'hhhh'} if __name__ == '__main__': dict_test()
Memory changes are as follows:
(2) immutable objects: int, string, float, tuple
def int_test(): i = 77 j = 77 print(id(77)) #140396579590760 print('i id:' + str(id(i))) #i id:140396579590760 print('j id:' + str(id(j))) #j id:140396579590760 print i is j #True j = j + 1 print('new i id:' + str(id(i))) #new i id:140396579590760 print('new j id:' + str(id(j))) #new j id:140396579590736 print i is j #False if __name__ == '__main__': int_test()
Memory allocation is as follows:
2, assignments, shallow copy and deep copy:
(1) b = a: assignment references, a and b are the same object.
(2) b = a.copy () : shallow copy, a and b are a separate object, sub-object, or they point to a unified object (reference).
(3) b = copy.deepcopy (a ): a deep copy, a and b complete copy of the parent object and its children, the two are completely separate.
3. More examples:
#!/usr/bin/python # -*-coding:utf-8 -*- import copy a = [1, 2, 3, 4, ['a', 'b']] #原始对象 b = a #赋值,传对象的引用 c = copy.copy(a) #对象拷贝,浅拷贝 d = copy.deepcopy(a) #对象拷贝,深拷贝 a.append(5) #修改对象a a[4].append('c') #修改对象a中的['a', 'b']数组对象 print( 'a = ', a ) print( 'b = ', b ) print( 'c = ', c ) print( 'd = ', d )
运行结果如下:
('a = ', [1, 2, 3, 4, ['a', 'b', 'c'], 5]) ('b = ', [1, 2, 3, 4, ['a', 'b', 'c'], 5]) ('c = ', [1, 2, 3, 4, ['a', 'b', 'c']]) ('d = ', [1, 2, 3, 4, ['a', 'b']])
4、按照具体需求选择合适的赋值或者拷贝形式:
建议:在内存足够的情况下,选择深拷贝,这样逻辑处理独立,不会产生上下文的影响,不容易发生难以解决的bug。