Printing a dictionary of class instances
Alex Martelli
aleax at aleax.it
Mon Mar 24 17:54:20 EST 2003
Grant Ito wrote:
> I have created a dictionary where the values are instances of a class. I'm
> wondering if it's possible to use the format operator (%) to access an
> instance member variable.
>
> sample:
>>>> dict1 = {'a' : 1}
>>>> print "%(a)s" % (dict1)
> 1
>>>> class testclass(object):
> ... def __init__(self):
> ... self.var1 = 1
> ... return
> ...
>>>> oneInstance = testclass()
>>>> testdict = {}
>>>> testdict['a'] = oneInstance
>>>> testdict['a'].var1
> 1
>>>> print "%(a.var1)s" % (testdict)
> Traceback (most recent call last):
> File "<interactive input>", line 1, in ?
> KeyError: a.var1
>
> Is there any way to write that last "print" line to make this work?
Only by using as testdict, not a dictionary, but a smart mapping
that knows how you want to use dots as separators. E.g. for just
one level of dots:
class dotdict(dict):
def __getitem__(self, key):
realkey, attrname = key.split('.', 1)
obj = dict.__getitem__(self, realkey)
return getattr(obj, attrname)
testdict = dotdict({'a': oneInstance})
Alex
More information about the Python-list
mailing list