Dynamically naming objects.

Hans Nowak zephyrfalcon!NO_SPAM! at gmail.com
Sat Jun 7 12:58:39 EDT 2008


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/



More information about the Python-list mailing list