Object Cloning

Clone objects using the copy module (shallow and deep copy).

IntermediateTopic: Object-Oriented Programs
Back

Python Object Cloning Program

This program helps you to learn the fundamental structure and syntax of Python programming.

Try This Code
# Program to demonstrate object cloning

import copy

class Node:
    def __init__(self, value, next=None):
        self.value = value
        self.next = next


n1 = Node(1, Node(2))
shallow = copy.copy(n1)
deep = copy.deepcopy(n1)

print("Original next:", n1.next)
print("Shallow next:", shallow.next)
print("Deep next:", deep.next)
Output
Original next: <__main__.Node object at ...>
Shallow next: <__main__.Node object at ...>
Deep next: <__main__.Node object at ...>

Understanding Object Cloning

copy.copy shares nested objects, while copy.deepcopy clones the entire object graph.

Note: To write and run Python programs, you need to set up the local environment on your computer. Refer to the complete article Setting up Python Development Environment. If you do not want to set up the local environment on your computer, you can also use online IDE to write and run your Python programs.

Table of Contents