Getting the class name of an instance?


Question

How do I find out a name of class that created an instance of an object in Python if the function I am doing this from is the base class of which the class of the instance has been derived?

Was thinking maybe the inspect module might have helped me out here, but it doesn't seem to give me what I want. And short of parsing the __class__ member, I'm not sure how to get at this information.

1
1243
9/7/2018 9:09:17 AM

Accepted Answer

Have you tried the __name__ attribute of the class? ie type(x).__name__ will give you the name of the class, which I think is what you want.

>>> import itertools
>>> x = itertools.count(0)
>>> type(x).__name__
'count'

This method works with new-style classes only. Your code might use some old-style classes. The following works for both:

x.__class__.__name__
1647
12/11/2015 5:59:26 AM

Do you want the name of the class as a string?

instance.__class__.__name__

Licensed under: CC-BY-SA with attribution
Not affiliated with: Stack Overflow
Icon