[Tutor] references to containing objects

Chris Fuller cfuller084 at thinkingplanet.net
Mon Jun 23 11:58:45 CEST 2008


You can also subclass the dictionary type so that this happens transparently.  
You could do something similar with lists.

class Container(dict):
   def __setitem__(self, key, value):
      dict.__setitem__(self, key, value)
      if hasattr(value, 'setParent'):
         if callable(value.setParent):
            value.setParent(self)

class Contained:
   def setParent(self, p):
      self.parent = p

bag = Container()
print id(bag)

item1 = Contained()
item2 = Contained()

bag['a'] = item1
bag['b'] = item2

print id(item1.parent)
print id(item2.parent)


Cheers


More information about the Tutor mailing list