Skip to content

Instantly share code, notes, and snippets.

@germantellezv
Forked from ferdef/prototype.py
Created March 20, 2019 05:15
Show Gist options
  • Save germantellezv/0cc6214dc9e521f1b8e22920a0b22367 to your computer and use it in GitHub Desktop.
Save germantellezv/0cc6214dc9e521f1b8e22920a0b22367 to your computer and use it in GitHub Desktop.
Prototype Pattern
from copy import deepcopy
class Prototype:
def __init__(self):
self._objects = {}
def register_object(self, name, obj):
'''Store an object so it can be cloned later'''
self._objects[name] = obj
def unregister_object(self, name):
'''Removes an object from our store'''
del self._objects[name]
def clone(self, name, **attr):
'''clone a registered object and add/replace attributes'''
obj = deepcopy(self._objects[name])
obj.__dict__.update(attr)
return obj
class Test:
first_name = None
prototype = Prototype()
test1 = Test()
test1.first_name = "John"
print(test1.first_name)
prototype.register_object('John', test1)
test2 = prototype.clone('John', first_name='Sam')
print(test2.first_name)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment