flyweight.py 1.0 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243
  1. #!/usr/bin/env python
  2. # -*- coding: utf-8 -*-
  3. """http://codesnipers.com/?q=python-flyweights"""
  4. import weakref
  5. class Card(object):
  6. """The object pool. Has builtin reference counting"""
  7. _CardPool = weakref.WeakValueDictionary()
  8. """Flyweight implementation. If the object exists in the
  9. pool just return it (instead of creating a new one)"""
  10. def __new__(cls, value, suit):
  11. obj = Card._CardPool.get(value + suit, None)
  12. if not obj:
  13. obj = object.__new__(cls)
  14. Card._CardPool[value + suit] = obj
  15. obj.value, obj.suit = value, suit
  16. return obj
  17. # def __init__(self, value, suit):
  18. # self.value, self.suit = value, suit
  19. def __repr__(self):
  20. return "<Card: %s%s>" % (self.value, self.suit)
  21. if __name__ == '__main__':
  22. # comment __new__ and uncomment __init__ to see the difference
  23. c1 = Card('9', 'h')
  24. c2 = Card('9', 'h')
  25. print(c1, c2)
  26. print(c1 == c2)
  27. print(id(c1), id(c2))
  28. ### OUTPUT ###
  29. # <Card: 9h> <Card: 9h>
  30. # True
  31. # 140368617673296 140368617673296