Getting the class name of an instance
To get the class name of an instance in Python, apply the instance.__class__.__name__
formula:
This provides the class name as a string for any instance, referred to as 'instance'.
Class name retrieval 101
Here's your toolkit for getting the class name of an instance in Python. Keep these snippets up your sleeve:
type() method: New kid on the block
With new-style classes (most commonly used in Python 3 and Python 2.2+), grab the class name with type(instance).__name__
:
New-style classes come to life by inheriting from object
. Remember, sharing is caring:
instance.class.name: Oldie but goldie
The instance.__class__.__name__
expression works like a charm with old-style classes and is universally compatible:
Self-aware classes: Gazing at the mirror
Inside a class method, use type(self).__name__
to get the class name. It's like asking, "Mirror, mirror on the wall, what's my class name after all?"
Full package identification: Full steam ahead
In cases where classes of the same name exist across different modules, bring out the heavy artillery with the module name and the class name together:
type() vs class: Choose wisely
The line between type()
and __class__
might blur at times. Old-style vs New-style classes are notorious for their subtleties, so get acquainted with them in the Python Wiki.
Inspect-free zone: Keeping it simple
Keeping things simple is key, therefore almost always, creating an __inspect__
module to fiddle with class names is overkill. Stick to type()
and __name__
for a more simple way out.
Sailing through pitfalls
While solutions abound, just like any journey, you might encounter bumps on the road. Here's what to watch out for:
Unusual suspects: Not all follow the rules
Behold! Some instances might override class retrieval methods:
Was this article helpful?