[Tutor] setattr question

Brad Reisfeld brad.reisfeld@colostate.edu
Mon, 18 Feb 2002 12:21:01 -0700


Hi,
I have a class with many properties that are dictionaries. I am trying to
set the values of these properties via setattr, but am having no luck.

I thought that since 'setattr(object, name, value)' should be the same as
'object.name = value', the following would work:

>>> class settest:
... 	def __init__(self):
... 		self.foo = {'prop1': 123, 'prop2': 456}
... 		return
...
>>> m = settest()
>>> m.foo['prop1'] = 987
>>> m.foo
{'prop2': 456, 'prop1': 987}
>>> setattr(m,foo['prop2'],654)
Traceback (most recent call last):
  File "<interactive input>", line 1, in ?
NameError: name 'foo' is not defined
>>> setattr(m.foo,'prop2',654)
Traceback (most recent call last):
  File "<interactive input>", line 1, in ?
TypeError: object has read-only attributes


What is the proper way to set values in an object's property dictionary via
setattr? Is this possible?

Thanks.

-Brad