How to get the class name of an object in Python
Published on Aug. 22, 2023, 12:15 p.m.
To get the class name of an object in Python, you can use the type() function or the .__class__.__name__ attribute. Here’s an example using type():
class MyClass:
pass
obj = MyClass()
class_name = type(obj).__name__
print(class_name)
In this example, we create a new class MyClass, and then create an object obj of that class. Then, we use the type() function to get the type of the object, and access the __name__ attribute to get the name of the class as a string. The resulting class name is then printed to the console.
Alternatively, you can also use the .__class__.__name__ attribute to get the name of the class as a string directly from the object, like this:
class_name = obj.__class__.__name__
print(class_name)
This will give the same result as the previous example.