Object Cloning in Python
Clone objects using the copy module (shallow and deep copy).
IntermediateObject-Oriented ProgramsExample 19 of 25
object-cloning.py
Run in browser1# Program to demonstrate object cloning23import copy45class Node:6 def __init__(self, value, next=None):7 self.value = value8 self.next = next910n1 = Node(1, Node(2))11shallow = copy.copy(n1)12deep = copy.deepcopy(n1)1314print("Original next:", n1.next)15print("Shallow next:", shallow.next)16print("Deep next:", deep.next)
Output
Original next: <__main__.Node object at ...> Shallow next: <__main__.Node object at ...> Deep next: <__main__.Node object at ...>
What's going on
copy.copy shares nested objects, while copy.deepcopy clones the entire object graph.