Velocity Reviews - Computer Hardware Reviews

Velocity Reviews > Newsgroups > Programming > Python > dictionary as property

Reply
Thread Tools

dictionary as property

 
 
Thanos Tsouanas
Guest
Posts: n/a
 
      07-19-2005
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?

Thanks in advance.

--
Thanos Tsouanas .: My Music: http://www.thanostsouanas.com/
http://thanos.sians.org/ .: Sians Music: http://www.sians.org/
 
Reply With Quote
 
 
 
 
Benjamin Niemann
Guest
Posts: n/a
 
      07-20-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/
 
Reply With Quote
 
 
 
Reply

Thread Tools

Posting Rules
You may not post new threads
You may not post replies
You may not post attachments
You may not edit your posts

BB code is On
Smilies are On
[IMG] code is On
HTML code is Off
Trackbacks are On
Pingbacks are On
Refbacks are Off


Similar Threads
Thread Thread Starter Forum Replies Last Post
Performance ordered dictionary vs normal dictionary Navkirat Singh Python 6 07-29-2010 10:18 AM
Re: Performance ordered dictionary vs normal dictionary Chris Rebert Python 0 07-29-2010 06:11 AM
creating a dictionary from a dictionary with regex james_027 Python 1 08-22-2007 07:39 AM
[DICTIONARY] - Copy dictionary entries to attributes Ilias Lazaridis Python 6 02-21-2006 11:27 AM
dictionary within dictionary Fox ASP General 5 03-13-2005 05:03 AM



Advertisments