borg.py 888 B

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152
  1. #!/usr/bin/env python
  2. # -*- coding: utf-8 -*-
  3. class Borg:
  4. __shared_state = {}
  5. def __init__(self):
  6. self.__dict__ = self.__shared_state
  7. def __str__(self):
  8. return self.state
  9. class YourBorg(Borg):
  10. pass
  11. if __name__ == '__main__':
  12. rm1 = Borg()
  13. rm2 = Borg()
  14. rm1.state = 'Idle'
  15. rm2.state = 'Running'
  16. print('rm1: {0}'.format(rm1))
  17. print('rm2: {0}'.format(rm2))
  18. rm2.state = 'Zombie'
  19. print('rm1: {0}'.format(rm1))
  20. print('rm2: {0}'.format(rm2))
  21. print('rm1 id: {0}'.format(id(rm1)))
  22. print('rm2 id: {0}'.format(id(rm2)))
  23. rm3 = YourBorg()
  24. print('rm1: {0}'.format(rm1))
  25. print('rm2: {0}'.format(rm2))
  26. print('rm3: {0}'.format(rm3))
  27. ### OUTPUT ###
  28. # rm1: Running
  29. # rm2: Running
  30. # rm1: Zombie
  31. # rm2: Zombie
  32. # rm1 id: 139825262601040
  33. # rm2 id: 139825262601104
  34. # rm1: Zombie
  35. # rm2: Zombie
  36. # rm3: Zombie