Access class instance "name" dynamically in Python
<p>In plain english:  I am creating class instances dynamically in a for loop, the class then defines a few attributes for the instance.  I need to later be able to look up those values in another for loop.</p>

<p>Sample code:</p>

<pre><code>class A:
    def __init__(self, name, attr):
        self.name=name
        self.attr=attr

names=("a1", "a2", "a3")
x=10
for name in names:
    name=A(name, x)
    x += 1
...
...
...
for name in names:
    print name.attr
</code></pre>

<p>How can I create an identifier for these instances so they can be accessed later on by "name"?</p>

<p>I've figured a way to get this by associating "name" with the memory location:</p>

<pre><code>class A:
    instances=[]
    names=[]
    def __init__(self, name, attr):
        self.name=name
        self.attr=attr
        A.instances.append(self)
        A.names.append(name)

names=("a1", "a2", "a3")
x=10
for name in names:
    name=A(name, x)
    x += 1
...
...
...
for name in names:
    index=A.names.index(name)
    print "name:  " + name
    print "att:  " + str(A.instances[index].att)
</code></pre>

<p>This has had me scouring the web for 2 days now, and I have not been able to find an answer.  Maybe I don't know how to ask the question properly, or maybe it can't be done (as many other posts seemed to be suggesting).</p>

<p>Now this 2nd example works, and for now I will use it.  I'm just thinking there has to be an easier way than creating your own makeshift dictionary of index numbers and I'm hoping I didn't waste 2 days looking for an answer that doesn't exist.  Anyone have anything?</p>

<p>Thanks in advance,
Andy</p>

<p>Update:  A coworker just showed me what he thinks is the simplest way and that is to make an actual dictionary of class instances using the instance "name" as the key.</p>
