I'm probably overlooking something simple. Given an instance of a class, I'd like to get just the class name. For example:
class Foooo: pass
instance = Foooo()
print("instance.__class__ = "+str(instance.__class__))
print("Just the class name: "+str(instance.__class__).split(".")[-1][:-2])
This gives the following output:
instance.__class__ = <class '__main__.Foooo'>
Just the class name: Foooo
Is there something simpler than
str(instance.__class__).split(".")[-1][:-2]?
I'm in Python 3.2 if that helps...
__class__ is an attribute on the object that refers to the class from which the object was created. a. __class__ # Output: <class 'int'> b. __class__ # Output: <class 'float'> After simple data types, let's now understand the type function and __class__ attribute with the help of a user-defined class, Human .
The first and easiest method to get a class name in python is by using __class__ property which basically refers to the class of the object we wish to retrieve. Here we combine the property with __name__ property to identify the class name of the object or instance.
The simplest way is to call the getClass() method that returns the class's name or interface represented by an object that is not an array. We can also use getSimpleName() or getCanonicalName() , which returns the simple name (as in source code) and canonical name of the underlying class, respectively.
How to Print the Type of a Variable in Python. To get the type of a variable in Python, you can use the built-in type() function. In Python, everything is an object. So, when you use the type() function to print the type of the value stored in a variable to the console, it returns the class type of the object.
Try this:
instance.__class__.__name__
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With