How to Get Class Name in Python
A python is an object-oriented programming language, and almost everything is an object, with its properties and methods. In Python, use the type(object) function to return a type object. To access the classname of the type of the object, use the __name__ attribute.
A Class in Python is like an object constructor or a “blueprint” for creating objects.
Get Class Name in Python
To get the class name of an instance in Python, use one of the following ways.
- Using the combination of type() Function and __name__ to get the type or class of the Object/Instance.
- Using the combination of the __class__ and __name__ to get the type or class of the Object/Instance.
The type() function is used to get the data type of the Python object.
Let’s take a simple example of string and check out its class name.
data = "Playstation 5" print(type(data).__name__)
As you can see that the class of string instance is str.
Let’s use the itertools module and use its repeat instance and get its class name.
import itertools data = itertools.repeat(1) print(type(data).__name__)
Let’s define an empty list and find the class of the list instance.
a_list =  data_type = type(a_list) class_name = data_type.__name__ print(class_name)
If you are using Python 2.x, then the following syntax will work for you.
You can also get the name of the class as a string.
class K: pass k = K() print(str(k.__class__))
That’s it for this tutorial.