prototype.py 762 B

1234567891011121314151617181920212223242526272829303132333435363738
  1. import copy
  2. class Prototype:
  3. def __init__(self):
  4. self._objects = {}
  5. def register_object(self, name, obj):
  6. """Register an object"""
  7. self._objects[name] = obj
  8. def unregister_object(self, name):
  9. """Unregister an object"""
  10. del self._objects[name]
  11. def clone(self, name, **attr):
  12. """Clone a registered object and update inner attributes dictionary"""
  13. obj = copy.deepcopy(self._objects.get(name))
  14. obj.__dict__.update(attr)
  15. return obj
  16. def main():
  17. class A:
  18. pass
  19. a = A()
  20. prototype = Prototype()
  21. prototype.register_object('a', a)
  22. b = prototype.clone('a', a=1, b=2, c=3)
  23. print(a)
  24. print(b.a, b.b, b.c)
  25. if __name__ == '__main__':
  26. main()