[Tutor] Creating an Identifier or Object Name from a String?

Dan Shafer pydan@danshafer.com
Tue, 11 Jun 2002 15:14:01 -0700


I think I was putting the eval step in the wrong place or something. 
Anyway, thanks to your comment and Danny Yoo's feedback, I got my program 
working just fine so it does the right thing with lists and with dictionaries.

Thanks!

At 10:35 AM 6/11/2002 +0200, Gregor Lingl wrote:
>I Tried it and it worked (?!)
>
>Python 2.2c1 (#27, Dec 14 2001, 13:15:16) [MSC 32 bit (Intel)] on win32
>Type "copyright", "credits" or "license" for more information.
>IDLE 0.8 -- press F1 for help
> >>> class K:
>         pass
>
> >>> field1 = K()
> >>> field2 = K()
> >>> field3 = K()
> >>> for ct in range(1,4):
>         obj="field"+str(ct)
>         objTC=eval(obj)
>         objTC.text=['a','b',str(ct)]
>
>
> >>> field1.text
>['a', 'b', '1']
> >>> field2.text
>['a', 'b', '2']
> >>> field3.text
>['a', 'b', '3']
> >>>
>
>Gregor
>
>
>Dan Shafer schrieb:
>
> > I have a need to refer to a number of objects which have been named field1,
> > field2, field3, etc. I want to set a property in each object in a loop.
> >
> > I thought this should work:
> >
> >    for ct in range(1,4):
> >      objToUpdate = "field" + str(ct)
> >      objToChange = eval(objToUpdate) # seems like it should produce
> > "field1" first time through the loop, etc.
> >      objToChange.text = inputList[ct] #inputList is generated prior to
> > entering the loop and is a list of string values
> >
> > This produces an error indicating that string objects don't have a text
> > attribute. So clearly objToChange is still a string at this point.
> >
> > I suspect this is tricky but if someone could help....
> >
> > Dan Shafer, Chief Scribe and Tablet Keeper
> > PythonCard Open Source Project
> > http://pythoncard.sourceforge.net
> >
> > _______________________________________________
> > Tutor maillist  -  Tutor@python.org
> > http://mail.python.org/mailman/listinfo/tutor

Dan Shafer, Chief Scribe and Tablet Keeper
PythonCard Open Source Project
http://pythoncard.sourceforge.net