Skip to main content
Stack Overflow
  1. About
  2. For Teams

You are not logged in. Your edit will be placed in a queue until it is peer reviewed.

We welcome edits that make the post easier to understand and more valuable for readers. Because community members review edits, please try to make the post substantially better than how you found it, for example, by fixing grammar or adding additional resources and hyperlinks.

Required fields*

Required fields*

Getting the class name of an instance

How do I find out the name of the class used to create an instance of an object in Python?

I'm not sure if I should use the inspect module or parse the __class__ attribute.

Answer*

Draft saved
Draft discarded
Cancel
5
  • 13
    I like this one. This way, it is possible in a base class to get the name of the subclass. Commented Jun 4, 2012 at 11:43
  • 19
    or self.__class__.__name__ instead of type(self).__name__ to get the same behaviour. Unless there is something the type() function does that I am not aware of? Commented Aug 20, 2012 at 21:47
  • 4
    If you're using type(item) on a list item the result will be <type 'instance'> while item.__class__.__name__ holds the class name. Commented Aug 6, 2014 at 9:43
  • 1
    I think the issue that @Grochni mentions is only relevant for certain classes in Python 2.x, see here: stackoverflow.com/questions/6666856/… Commented Feb 22, 2015 at 18:09
  • @andreb The original solution is shorter. Commented Mar 8, 2023 at 15:27

lang-py

AltStyle によって変換されたページ (->オリジナル) /