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.
Learn Flask development and learn to build cool apps with our premium Python course on Udemy.