flyweight.py 1.0 KB

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