Want more features on Pastebin? Sign Up, it's FREE!
Guest

http://stackoverflow.com/questions/12359366

By: a guest on Sep 10th, 2012  |  syntax: Python  |  size: 0.91 KB  |  views: 34  |  expires: Never
download  |  raw  |  embed  |  report abuse  |  print
Text below is selected. Please press Ctrl+C to copy to your clipboard. (⌘+C on Mac)
  1. import weakref
  2. import copy
  3.  
  4. class Card(object):
  5.  
  6.         _CardPool = weakref.WeakValueDictionary()
  7.  
  8.         def __new__(cls, value, suit, **kwargs):
  9.                 obj = Card._CardPool.get(value + suit, None)
  10.                 if not obj:
  11.                         obj = object.__new__(cls)
  12.                         obj.value, obj.suit = value, suit
  13.                         Card._CardPool[value + suit] = obj
  14.                 return obj
  15.  
  16.  
  17. class MyObj(object):
  18.         def __init__(self, value, suit):
  19.                 super(MyObj, self).__setattr__('_internal', Card(value, suit))
  20.  
  21.         def __setattr__(self, name, new_value):
  22.                 vals = self._internal.__dict__
  23.                 if name in vals.keys():
  24.                         vals = vals.copy()
  25.                         vals[name] = new_value
  26.                         card = Card(**vals)
  27.                         super(MyObj, self).__setattr__('_internal', card)
  28.                 else:
  29.                         super(MyObj, self).__setattr__(name, new_value)
  30.  
  31.         def __getattr__(self, name):
  32.                 try:
  33.                         return getattr(self._internal, name)
  34.                 except AttributeError:
  35.                         raise AttributeError("'MyObj' object has no attribute '%s'" % name)
clone this paste RAW Paste Data