Guest User

http://stackoverflow.com/questions/12359366

a guest
Sep 10th, 2012
200
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 0.91 KB | None | 0 0
  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)
Add Comment
Please, Sign In to add comment