python- shallow copy and deep copy

  • Direct assignment: in fact, object reference (alias).

  • Shallow copy (copy): sub-objects inside a copy of the parent object, the object will not be copied.

  • Deep copy (DeepCopy):  DeepCopy method copy module, complete copy of the parent object and child objects.




= {dict1 'User': 'runoob', 'NUM': [. 1, 2,. 3]}

dict2 shallow copy # = dict1: reference object
dict3 = dict1.copy () # shallow copy: deep copy of the parent object (a directory), sub-objects (level two) do not copy, or reference

# modify data data
dict1 [ 'User'] = 'the root'
dict1 [ 'num']. remove (1) # 1 is removed in the keyword num

# output
Print (dict1)
Print (dict2)
Print (dict3)

{ 'user': 'root' , 'num': [2, 3]} # of dict1 assignment changes
{ 'user': 'root' , 'num': [2, 3]} # diect2 shallow copy, dict2
{ 'User': 'runoob', 'NUM': [2,. 3]} # deep copy, copy method invocation

dict2 fact dict1 reference (alias), the output results are consistent, dict3 deep copy of the parent object, without modification with the modifying dict1 (renoob not changed), the child object is so shallow copy of modifications with dict1 modify

Guess you like

Origin www.cnblogs.com/yezimama/p/11009063.html