class MyClass: pass obj = MyClass() class_name = obj.__class__.__name__ print(class_name)
MyClass
In Python, you can use the __class__ attribute to get the class of an instance as seen in the code above.
You can also use the type() built-in function to get the class of an instance:
class_name = type(obj).__name__ print(class_name) # Output: "MyClass"Or you can use the classmethod built-in function __class__ and assign the result to a variable:
class_name = obj.__class__.__name__ print(class_name) # Output: "MyClass"Both __class__ and type() will return the class of the instance, but __class__ is an instance method and type() is a built-in function.
Python Mega Course: Learn Python in 60 Days, Build 20 Apps
Learn Python on Udemy completely in 60 days or less by building 20 real-world applications from web development to data science.