Steven D'Aprano <[EMAIL PROTECTED]> writes: > On Sat, 23 Jul 2005 11:48:27 +0300, Thanos Tsouanas wrote: >> Hello. >> >> I would like to have a quick way to create dicts from object, so that a >> call to foo['bar'] would return obj.bar. > > That looks rather confusing to me. Why not just call obj.bar, since it > doesn't look like you are actually using the dictionary at all?
Well, I needed exactly this functionality last week. I have a collection of (rather messy) classes that have a slew of attributes as values. I would have used a dictionary for this, but I didn't write the code. I have to be able to display these objects (in HTML, if it matters), and have as a requirement that the format string live in a database. My solution didn't look to different from dictobj. There's some extra mechanism to fetch the format string from the database, and some formatting of the attribute based on meta-information in the object, but it's the same basic idea. >> class dictobj(dict): >> """ >> class dictobj(dict): >> A dictionary d with an object attached to it, >> which treats d['foo'] as d.obj.foo. >> """ >> def __init__(self, obj): >> self.obj = obj >> def __getitem__(self, key): >> return self.obj.__getattribute__(key) > > I don't think this is particularly useful behaviour. How do you use it? def __str__(self): return self._format % self <mike -- Mike Meyer <[EMAIL PROTECTED]> http://www.mired.org/home/mwm/ Independent WWW/Perforce/FreeBSD/Unix consultant, email for more information. -- http://mail.python.org/mailman/listinfo/python-list