Dynamically naming objects.

Kalibr space.captain.face at gmail.com
Sat Jun 7 18:36:44 EDT 2008


On Jun 8, 2:58 am, Hans Nowak <zephyrfalcon!NO_SP... at gmail.com> wrote:
> Kalibr wrote:
> > On Jun 7, 1:20 pm, Hans Nowak <zephyrfalcon!NO_SP... at gmail.com> wrote:
> >> Kalibr wrote:
> >>> I've been developing a small script to fiddle with classes, and came
> >>> accross the following problem. Assuming I get some user input asking
> >>> for a number, how would I spawn 'n' objects from a class?
> >>> i.e. I have a class class 'user' and I don't know how many of them I
> >>> want to spawn.
> >>> Any ideas?
> >> Sure. This will give you a list of n instances of user:
>
> >>    [user() for i in range(n)]
>
> >> Of course, you could also use a good old for loop:
>
> >>    for i in range(n):
> >>        u = user()
> >>        ...do something with u...
>
> >> Hope this helps!
>
> >> --
> >> Hans Nowak (zephyrfalcon at gmail dot com)http://4.flowsnake.org/
>
> > whoops, replied to author....
>
> > What I wanted to ask before was won't 'u' be overwritten with a new
> > object each time the loop ticks over?
>
> Yes, so you have to store it somewhere, if you want to keep the object around.
> The list comprehension mentioned above stores all the objects in a list, after
> which they can be accessed at will via indexing.
>
> > what I want to do is have, say 5 users in a game, so I'd have to spawn
> > 5 objects. I can't do that because I have'nt hardcoded any object
> > names for them.
>
> > or does it somehow work? how would I address them if they all have the
> > name 'u'?
>
> users = [user() for i in range(n)]
>
> # use: users[0], users[1], etc
>
> --
> Hans Nowak (zephyrfalcon at gmail dot com)http://4.flowsnake.org/

Ok, wait, I see where this is going.
I just did the list comprehension.
I was under some misguided idea that you actually had to have a unique
variable name for all the new objects you spawned. Thanks for all you
help guys!



More information about the Python-list mailing list