Naming class instances in real time
Fredrik Lundh
fredrik at pythonware.com
Mon Aug 12 15:46:07 EDT 2002
Neil MacMillan wrote:
> Is there a clean way for me to name class instances (or variables, or
> whathaveyou without hard-coding the names?
>
> For example, if I wanted to make objects representing people:
>
> >>>class People():
> ... pass
> ...
>
> Can I then have a limited but unknown number of instances of
> that class in a running program named:
>
> >>>person0 = People()
> >>>person1 = People()
> >>>person2 = People()
why not do like everyone else, and put your instances
in a list?
persons = []
for i in range(some_random_integer):
persons.append(People())
print person[0]
or even
persons = [People() for i in range(some_random_integer)]
> ...and so on until the number of instances of People() is equal
> to any randomly generated integer, and each instance is named
> "person"+integer?
it can be done, but as usual, Python works better if you use it
to write Python code.
</F>
More information about the Python-list
mailing list