Monday 21 October 2019

python - Getting the class name of an instance?



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.


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__

No comments:

Post a Comment

php - file_get_contents shows unexpected output while reading a file

I want to output an inline jpg image as a base64 encoded string, however when I do this : $contents = file_get_contents($filename); print &q...