Newbie question, I guess.

thedog thedog at linux.nu
Mon May 7 12:36:30 EDT 2001


Alex Martelli wrote:

> "thedog" <thedog at linux.nu> wrote in message
> news:3AF695A6.9E461EC5 at linux.nu...
> > Newbie question, I guess.
> > I have two variables direction and framenr
> >
> > direction = 'fw'
> > framenr = 1
> >
> > which I want to use in the following code to navigate round in my little
> > game.
>     ...
> > the problem is the line: frame = '%(direction)s%(framenr)simage' %vars()
> >
> > when using this a string is passed to frame(for example, when the up
> > arrow is pressed: the string ‘fw1image’). But I don’t want a string to
> > be passed to it just fw1image, because fw1image is a surface that later
> > will be shown on screen.
> >
> > So I want to change ‘fw1image’ to fw1image, is this possible?
>
> Yes,
>     frame = eval(frame)
> or
>     frame = vars()[frame]
> would do this.
>
> > Or if you know any better way of accomplishing this, enlighten me.
>
> It's probably beter to keep your "surfaces that later will be shown"
> into a dictionary rather than in separate variables that are only
> connected by having similar/systematic names.
>
> E.g.: instead of having
>     fw1image = animage()
>     fw2image = anotherimage()
>     # etc
> have
>     images = {}
>     images['fw',1] = animage()
>     images['fw',2] = anotherimage()
> (or, whatever else you currently do to bind these separate
> variables, do it instead to bind items in the dictionary
> called images).
>
> Now, instead of
>     frame = '%(direction)s%(framenr)simage' %vars()
>     frame = vars()[frame]
>
> you can use the simpler and clearer:
>     frame = images[direction, framenr]
>
> > PS. I’m sorry if the text is confusing, but I’m very very tired.
>
> No problem!  I hope I did understand your problems correctly.
>
> Needs to manipulate variable names, and get the objects from
> variable names that are held as strings, most often do come
> from not having used a dictionary, but rather a bunch of
> unrelated variables with similar systematic names, to hold
> certain items -- it seems to me that this general pattern is
> applicable to your case.  If it isn't, then we may need to
> dig further!
>
> Alex

Thank you very much for your help. You did understand my problems completely
right actually and you are totally right, that way you described it is of
course the right way to write it.

//thedog





More information about the Python-list mailing list