-
- Assigning values to Objects
- Shallow copy
- Deep copy
1. Assigning Values to Objects
An object's assignment is actually a reference to an object. This means that when an object is assigned to another object, only the reference is copied. Such as:
>>> t1 = tuple(‘furzoom‘)>>> t2 = t1>>> id(t1),id(t2)(139792198303936139792198303936)
Above T1 and T2 represent the same object.
2. Shallow copy
In addition to assigning an object directly to another object above, there are two common methods for copying objects: using slice operations and factory methods.
>>> car = [‘grand‘, [‘length‘4.85]]>>> a4 = car[:]>>> a6 = list(car)>>> forin car, a4, a6][‘0x7f23e84da2d8‘‘0x7f23e84da128‘‘0x7f23e84da3f8‘]
By creating cars A4 and A6, it does represent different objects. Now continue to refine A4 and A6, modify their names, and car lengths.
>>>a4[0] =' A4 '>>>a6[0] =' A6 '>>>A4, A6 ([' A4 ', [' Length ',4.85]], [' A6 ', [' Length ',4.85]])>>>a4[1][1] =4.761>>>A4, A6 ([' A4 ', [' Length ',4.761]], [' A6 ', [' Length ',4.761]])
When modifying the car's name, they behaved normally, and when the car commander was modified, the unexpected result was changed, the length of the A4 was modified, and the length of the A6 was also affected.
Why is that? The reason is that only a shallow copy is made for the sequence. The shallow copy of the sequence type object is the default copy, reflected in: copy function using slice operation [:], Factory function, copy module. When changing the name of the A6 car, why is it not reflected in the A4 car? This is because the name is a string type, it is an immutable type, and changing its contents will reference the newly created object. As follows:
>>>A8 = List (CAR)>>>[Hex (ID (x)) forXinchcar][' 0x7f23e84d7a80 ',' 0x7f23e84da320 ']>>>[Hex (ID (x)) forXincha8][' 0x7f23e84d7a80 ',' 0x7f23e84da320 ']>>>[Hex (ID (x)) forXincha4][' 0x7f23e84d4d78 ',' 0x7f23e84da320 ']>>>[Hex (ID (x)) forXincha6][' 0x7f23e84d4e40 ',' 0x7f23e84da320 ']
In the second entry of A4 and A6, they refer to the same object.
3. Deep copy
To avoid this effect, you need to make a deep copy of the list. You need to use the deepcopy () function of the copy module.
Such as:
>>>Car = [' Grand ', [' Length ',4.85]]>>>a4 = car>>>ImportCopy>>>A6 = copy.deepcopy (CAR)>>>[Hex (ID (x)) forXinchCar, A4, a6][' 0x7f23e84da098 ',' 0x7f23e84da098 ',' 0x7f23e84da440 ']>>>a4[0] =' A4 '>>>a6[0] =' A6 '>>>A4,A6 ([' A4 ', [' Length ',4.85]], [' A6 ', [' Length ',4.85]])>>>a4[1][1] =4.761>>>A4,A6 ([' A4 ', [' Length ',4.761]], [' A6 ', [' Length ',4.85]])
Also, in the Copy module, there are only two functions, copy
and deepcopy
.
Python object copy-deep copy and shallow copy