prototype.py 729 B

123456789101112131415161718192021222324252627282930313233343536
  1. from copy import deepcopy
  2. class Prototype:
  3. def __init__(self):
  4. self._objs = {}
  5. def registerObject(self, name, obj):
  6. """
  7. register an object.
  8. """
  9. self._objs[name] = obj
  10. def unregisterObject(self, name):
  11. """unregister an object"""
  12. del self._objs[name]
  13. def clone(self, name, **attr):
  14. """clone a registered object and add/replace attr"""
  15. obj = deepcopy(self._objs[name])
  16. obj.__dict__.update(attr)
  17. return obj
  18. if __name__ == '__main__':
  19. class A:
  20. pass
  21. a = A()
  22. prototype = Prototype()
  23. prototype.registerObject("a", a)
  24. b = prototype.clone("a", a=1, b=2, c=3)
  25. print(a)
  26. print(b.a, b.b, b.c)