[Tutor] object names

Alan Gauld alan.gauld at btinternet.com
Sun Jul 8 18:53:48 CEST 2007


"elis aeris" <hunter92383 at gmail.com> wrote 

> for instance, i need to create 5 object of names like these
> 
> object_1
> object_2
> and so on,

It's very unlikely that you need to do this.
The usual solution in cases like this is to store the objects 
in a collection object, either a list or a dictionary. You can 
then access them by index or name.

For example:

# create some objects with a list
objects = []
for n in range(5):
    objects.append(n)

# now fetch number 3
print objects[3]

# fetch them all in turn
for object in objects:
    print object

# repeat above with a dictionary
d = {}
for n in range(5):
    name = 'object_' + str(n)
    d[name] = n

# fetch object_3
print d['object_3']

# fetch all
for object in d.keys()
    print d[object]

If that solution won't work for you for some reason tell us 
why and we can provide ways to do what you need. But 
using a collection will work for the vast majority of cases.

HTH,

-- 
Alan Gauld
Author of the Learn to Program web site
http://www.freenetpages.co.uk/hp/alan.gauld



More information about the Tutor mailing list