Problem Statement:
In Python, creating a copy of an object may seem as simple as assigning one object to another. However, this simple assignment creates a reference to the original object instead of a new independent instance.Modifications to one object will propagate to the other.This can lead to unexpected behavior and potential bugs.
Solution: Deep Copying with copy.deepcopy()
To create a genuinely independent copy of an object, we employ the copy.deepcopy() function from the copy module. This function performs a deep copy, recursively copying all attributes and child objects of the original object.The resulting copy is an independent object with its own memory location and values.
Example:
<code class="python">import copy original_obj = {'name': 'Alice', 'age': 30} copy_obj = copy.deepcopy(original_obj) copy_obj['name'] = 'Bob' # Modify copy print(original_obj) # Output: {'name': 'Alice', 'age': 30} (Unchanged) print(copy_obj) # Output: {'name': 'Bob', 'age': 30} (Independent)</code>
In this case, copy_obj is genuinely independent from original_obj. Modifying one does not affect the other.This enables you to create multiple objects with distinct values while sharing the same initial properties.
Note:
Shallow copying, which can be achieved with copy.copy(), only copies the data structure's values,leaving any contained references as they were.Deep copying is generally preferred to ensure object independence.
The above is the detailed content of How to Create Independent Copies of Objects in Python?. For more information, please follow other related articles on the PHP Chinese website!