Getting the class name of an instance
To get the class name of an instance in Python, you can use the __class__
attribute of the object. For example:
class MyClass:
pass
obj = MyClass()
class_name = obj.__class__.__name__
print(class_name) # Output: "MyClass"
Watch a video course
Python - The Practical Guide
You can also use the type()
function to get the class name. The type()
function returns the type of the object, which is also the class name if the object is an instance of a class. For example:
class MyClass:
pass
obj = MyClass()
class_name = type(obj).__name__
print(class_name) # Output: "MyClass"
Alternatively, you can use the classname()
function defined below, which works for both Python 2 and Python 3:
class MyClass:
pass
obj = MyClass()
def classname(obj):
return obj.__class__.__name__
class_name = classname(obj)
print(class_name) # Output: "MyClass"