Re: dictionary as property
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/ -- http://mail.python.org/mailman/listinfo/python-list
dictionary as property
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/ -- http://mail.python.org/mailman/listinfo/python-list
Re: dictionary as property
On Tue, Jul 19, 2005 at 07:56:20PM +0300, 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? You could implement a custom container type that will do what you want. See http://docs.python.org/ref/sequence-types.html for __setitem__. Quick hack: class Foo: ... def __init__(self): ... self.d = self ... def __setitem__(self, key, value): ... getattr(self, key)(value) ... def bar(self, param): ... print bar got called with, param ... foo = Foo() foo.d[bar] = 42 bar got called with 42 -- Gerhard -- Gerhard Häring - [EMAIL PROTECTED] - Python, web database development signature.asc Description: Digital signature -- http://mail.python.org/mailman/listinfo/python-list
Re: dictionary as property
On Tue, Jul 19, 2005 at 07:00:10PM +0200, Gerhard Haering wrote: On Tue, Jul 19, 2005 at 07:56:20PM +0300, 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? You could implement a custom container type that will do what you want. See http://docs.python.org/ref/sequence-types.html for __setitem__. Thanks, that doc had all I needed :) -- Thanos Tsouanas .: My Music: http://www.thanostsouanas.com/ http://thanos.sians.org/ .: Sians Music: http://www.sians.org/ -- http://mail.python.org/mailman/listinfo/python-list