Copying Objects in Python
Creating an independent copy of an object is a common task in programming. In Python, there are two main ways to copy an object: shallow copying and deep copying.
Shallow Copying
Python's default copying mechanism is shallow copying. This means that a new object is created with a reference to the same fields as the original object. Any changes made to the fields of the new object will also be reflected in the original object.
Deep Copying
Deep copying, on the other hand, creates a new object with separate copies of the fields from the original object. This means that any changes made to the fields of the new object will not affect the original object.
To get a fully deep independent copy of an object in Python, you can use the copy.deepcopy() function. Here's an example:
<code class="python">import copy # Original object obj = { "name": "Alice", "age": 20 } # Create a shallow copy shallow_copy = obj # Create a deep copy deep_copy = copy.deepcopy(obj) # Modify the shallow copy shallow_copy["name"] = "Bob" # Print the original and deep copy print(obj) # Output: {'name': 'Bob', 'age': 20} print(deep_copy) # Output: {'name': 'Alice', 'age': 20}</code>
As you can see, the deep_copy retains the original values of the object, while the shallow_copy is affected by the changes made to the original object.
The above is the detailed content of How do Shallow and Deep Copying Differ in Python?. For more information, please follow other related articles on the PHP Chinese website!