[Tutor] How to generate instance names?

Terry Carroll carroll at tjc.com
Mon Nov 8 22:31:45 CET 2004


On Mon, 8 Nov 2004, Christopher Singley wrote:

> I am new to object-oriented programming, and have a basic question. 
> How can I generate an object name when creating an instance of a
> class, rather than hard-coding the name at creation?

When someone asks this, the answer is almost always they they should use 
dictionaries.
 
> I'd like to say something like this:
> --
> class Person(object):
>   def __init__(self,name):
>     self.name = name
> 
> names = ["Tom", "Dick", "Harry"]
> personlist = [ ]
> i=0
> for name in names:
>   dude"i" = Person(name)
>   personlist.append(dude"i")
>   i  += 1

How about:

names = ["Tom", "Dick", "Harry"]
dudes = {}
i=0
for name in names:
   dude[i] = Person(name)
   personlist.append(dude[i])
   i  += 1





More information about the Tutor mailing list