dictionary as property

Discussion in 'Python' started by Thanos Tsouanas, Jul 19, 2005.

  1. Thanos Tsouanas, Jul 19, 2005
    #1
    1. Advertising

  2. 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/
    Benjamin Niemann, Jul 20, 2005
    #2
    1. Advertising

Want to reply to this thread or ask your own question?

It takes just 2 minutes to sign up (and it's free!). Just click the sign up button to choose a username and then you can ask your own questions on the forum.
Similar Threads
  1. Ilias Lazaridis
    Replies:
    6
    Views:
    427
    Ilias Lazaridis
    Feb 21, 2006
  2. james_027
    Replies:
    1
    Views:
    309
    Marc 'BlackJack' Rintsch
    Aug 22, 2007
  3. Navkirat Singh
    Replies:
    6
    Views:
    2,969
    Navkirat Singh
    Jul 29, 2010
  4. Chris Rebert
    Replies:
    0
    Views:
    506
    Chris Rebert
    Jul 29, 2010
  5. Fox

    dictionary within dictionary

    Fox, Mar 8, 2005, in forum: ASP General
    Replies:
    5
    Views:
    170
    Michael D. Kersey
    Mar 13, 2005
Loading...

Share This Page