Printing a dictionary of class instances

Grant Ito Grant_Ito at shaw.ca
Mon Mar 24 19:41:52 CET 2003


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?


Many thanks,
Grant.






More information about the Python-list mailing list