dictionary as property

T

Thanos Tsouanas

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.
 
B

Benjamin Niemann

Thanos said:
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...
 

Ask a Question

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

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,755
Messages
2,569,536
Members
45,013
Latest member
KatriceSwa

Latest Threads

Top