prototype.py 1.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051
  1. #!/usr/bin/env python
  2. # -*- coding: utf-8 -*-
  3. import copy
  4. class Prototype:
  5. def __init__(self):
  6. self._objects = {}
  7. def register_object(self, name, obj):
  8. """Register an object"""
  9. self._objects[name] = obj
  10. def unregister_object(self, name):
  11. """Unregister an object"""
  12. del self._objects[name]
  13. def clone(self, name, **attr):
  14. """Clone a registered object and update inner attributes dictionary"""
  15. obj = copy.deepcopy(self._objects.get(name))
  16. obj.__dict__.update(attr)
  17. return obj
  18. class A:
  19. def __init__(self):
  20. self.x = 3
  21. self.y = 8
  22. self.z = 15
  23. self.garbage = [38, 11, 19]
  24. def __str__(self):
  25. return '{} {} {} {}'.format(self.x, self.y, self.z, self.garbage)
  26. def main():
  27. a = A()
  28. prototype = Prototype()
  29. prototype.register_object('objecta', a)
  30. b = prototype.clone('objecta')
  31. c = prototype.clone('objecta', x=1, y=2, garbage=[88, 1])
  32. print([str(i) for i in (a, b, c)])
  33. if __name__ == '__main__':
  34. main()
  35. ### OUTPUT ###
  36. # ['3 8 15 [38, 11, 19]', '3 8 15 [38, 11, 19]', '1 2 15 [88, 1]']