Get the instance name from a list by Reflection

Larry Bates larry.bates at websafe.com
Mon Oct 22 10:12:28 EDT 2007


Jean-Paul Calderone wrote:
> On Sat, 20 Oct 2007 21:10:34 +0200 (CEST), sccs cscs <zorg724 at yahoo.fr> 
> wrote:
>> Hello,
>> I cannot find into documentation how to get the instance name. I found 
>> the attributes __dict__,__class__ ,__bases__ __name__ ,
>> but if i have the code:
>>
>> class A :pass
>> a1 = A ()
>> a2 = A ()
>> aList = [a1,a2]
>> for elem in aList :
>>    print elem.__instance_name__ ???
>>
>> I expect to have "a1" "a2" ...
>> But it does not work ...
>> help please
>> Zorgi
> 
>    $ python
>    Python 2.4.3 (#2, Oct  6 2006, 07:52:30)
>    [GCC 4.0.3 (Ubuntu 4.0.3-1ubuntu5)] on linux2
>    Type "help", "copyright", "credits" or "license" for more information.
>    >>> class A: pass
>    ...
>    >>> a1 = A()
>    >>> a2 = A()
>    >>> aList = [a1, a2]
>    >>> import __main__
>    >>> from twisted.python.reflect import objgrep, isSame
>    >>> for elem in aList:
>    ...     objgrep(__main__, elem, isSame)
>    ...
>    ['.aList[0]', '.elem', '.a1']
>    ['.aList[1]', '.elem', '.a2']
>    >>>
> 
> Don't see how this could help,
> 
> Jean-Paul
If you want to accomplish something like this use the following:

class A(object):
     def __init__(self, name=None):
         self.name=name

aList=[]
aList.append(A(name='a1')
aList.append(A(name='a2')
for elem in aList:
     print elem.name

-Larry



More information about the Python-list mailing list