[Tutor] new object attribute from string?
Jeff Shannon
jeff@ccvcorp.com
Mon Apr 14 17:09:02 2003
Danny Yoo wrote:
>Yes, the direct way works too. *grin*
>
>In certain really dynamic code, the attribute name itself may not known
>until "runtime", when the program is actively running.
>
>
Under most such circumstances, though, wouldn't it be easier and more
straightforward to use setattr()/getattr() instead of directly fiddling
with the object's __dict__?
>>> class Item:
... pass
...
>>> i = Item()
>>> i.dict
Traceback (most recent call last):
File "<interactive input>", line 1, in ?
AttributeError: Item instance has no attribute 'dict'
>>> attribute = "dict"
>>> setattr(i, attribute, {})
>>> i.dict
{}
>>> getattr(i, attribute)
{}
>>>
Jeff Shannon
Technician/Programmer
Credit International