prototype.py 887 B

123456789101112131415161718192021222324252627282930313233343536373839404142434445
  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. def main():
  19. class A:
  20. pass
  21. a = A()
  22. prototype = Prototype()
  23. prototype.register_object('a', a)
  24. b = prototype.clone('a', a=1, b=2, c=3)
  25. print(a)
  26. print(b.a, b.b, b.c)
  27. if __name__ == '__main__':
  28. main()
  29. ### OUTPUT ###
  30. # <__main__.main.<locals>.A object at 0x7fc1d23272d0>
  31. # 1 2 3