Prototype Pattern in Python

Implement a simple Prototype pattern by cloning existing objects.

IntermediateObject-Oriented ProgramsExample 22 of 25
prototype-pattern.py
1# Program to implement a simple Prototype pattern
2
3import copy
4
5class Prototype:
6 def clone(self):
7 return copy.deepcopy(self)
8
9class Document(Prototype):
10 def __init__(self, title, content):
11 self.title = title
12 self.content = content
13
14doc1 = Document("Report", "Content here")
15doc2 = doc1.clone()
16doc2.title = "Report Copy"
17
18print(doc1.title)
19print(doc2.title)

Output

Report
Report Copy

What's going on

The base Prototype class offers a 'clone' method that subclasses can reuse to duplicate instances.

After this program

If the idea is still fuzzy, read Day 11: Classes and Objects in the Python course. For a short check, try the Python quiz (300 questions). Stay with all 25 object-oriented programs, or see every topic on Python exercises.