How to obtain an instance's name at runtime?

Charles G Waldman cgw at fnal.gov
Wed Jun 23 11:27:35 EDT 1999


Dinu C. Gherman writes:

 > >>> class C:
 > ...    pass
 > ...
 > >>>
 > >>> c = C()
 > >>> C.__class__.__name__ # ok
 > 'C'
 > >>> c.__name__           # not ok
 > Traceback (innermost last):
 >   File "<interactive input>", line 0, in ?
 > AttributeError: __name__
 > >>>
 > 
 > Question: How to obtain an instance's name at runtime?
 > That is I'd like to see this happen (one was or the other):
 > 
 > >>> c.__name__
 > 'c'
 > 
 > Fearing-there's-no-such-solution'ly,

Do not fear!  Simply write

 >>> c.__class__.__name__
 'C'

















More information about the Python-list mailing list