in this python tutorial, I’ll let you know how to get a class name in python. As we know, Python is an object-oriented programming language, and everything represent is an object. To access the class name of the type of the object, use the __name__ attribute.
I have already shared Python Classes Tutorials with Example
Class in Python
The Class is a blueprint for creating an object. You can combine data(attributes) and functionality(methods) together using the python class. Each class instance can have attributes attached to it for maintaining its state, also has methods for modifying its state.
How To Get class name in Python
The type()
a function is used to get the data type of the Python object.
- To get the type or class of an Object/Instance, use the type() method and __name__.
- The type or class of the Object/Instance can be determined by combining the __class__ and __name__ variables.
Let’s look at a basic string and see what class it belongs to.
data = "pythonpip" print(type(data).__name__)
Output:
str
Let’s create an empty list and figure out what class the list instance belongs to.
a_list = [] data_type = type(a_list) class_name = data_type.__name__ print(class_name)
Output:
list
How to Check Class name in Python 2X
If you are using Python 2.x, the following syntax will be used to get the class name type.
data.__class__.__name__
You can also get the name of the class as a string.
class Test: pass t = Test() print(str(t.__class__))
Output:
<class '__main__.Test'>