dictionary as property

Benjamin Niemann pink at odahoda.de
Wed Jul 20 04:33:10 EDT 2005


Thanos Tsouanas wrote:

> Hello.
> 
> (How) can I have a class property d, such that d['foo'] = 'bar' will run
> a certain function of the class with 'foo' and 'bar' as it's arguments?

I think you mean:

class A:
  def __init__(self):
    self.d = {}

  def dict_change(self, key, value):
    print key, value

a = A()
a.d['foo'] = 'bar'
--> foo bar

'a' only has a reference to 'd', it won't know, who has a copy of this
reference and what done to it.
What you could create, is a wrapper around 'd', that passes __getitem__,
__setitem__ and every other required method to the underlying dict and call
the appropriate hook method of A

class WrappedDict:
  def __init__(self, owner, d):
    self.owner = owner
    self.d = d

  def __setitem__(self, key, value):
    self.owner.dict_changed(key, value)
    self.d[key] = value

  def __getitem(self, key):
    return self.d[key]

  ....

And in A.__init__
  self.d = WrappedDict(self, {})

You may also subclass WrappedDict from dict...

-- 
Benjamin Niemann
Email: pink at odahoda dot de
WWW: http://www.odahoda.de/



More information about the Python-list mailing list