For example
a = {"key1":"value1"}
b = a
a["key1"] = "value2"
print a
>> {"key1":"value2"}
print b
>> {"key1":"value2"}
However if we need to copy by reference we can use the:
- copy.copy(x)
- Return a shallow copy of x.
- copy.deepcopy(x)
- Return a deep copy of x.
Methods from the library "copy".
The difference between shallow and deep copying is only relevant for compound objects (objects that contain other objects, like lists or class instances):
- A shallow copy constructs a new compound object and then (to the extent possible) inserts references into it to the objects found in the original.
- A deep copy constructs a new compound object and then, recursively, inserts copies into it of the objects found in the original.
The example above could now be rewritten like below:
import copy
a = {"key1":"value1"}
b = copy.deepcopy(a)
a["key1"] = "value2"
print a
>> {"key1":"value2"}
print b
>> {"key1":"value1"}
No comments:
Post a Comment