Skip to content
Home / Fundamentals

Get the class name of an instance in Python

In Python, you can get the class name of an instance using the __class__ attribute or the type() function. The __class__ attribute returns the class object of the instance, while the type() function returns the type of the object.

Here's an example of using the __class__ attribute to get the class name of an instance:

class MyClass:
    pass

obj = MyClass()
class_name = obj.__class__.__name__
print(class_name)  # Output: "MyClass"

You can also use the type()() function to get the class name of an instance, like this:

class MyClass:
    pass

obj = MyClass()
class_name = type(obj).__name__
print(class_name)  # Output: "MyClass"

You can also use the type() function to check the type() of an object, like this:

class MyClass:
    pass

obj = MyClass()
if type(obj) == MyClass:
    print("obj is an instance of MyClass")
else:
    print("obj is not an instance of MyClass")

Alternatively, you can use the isinstance() function to check if an object is an instance of a particular class, like this:

class MyClass:
    pass

obj = MyClass()
if isinstance(obj, MyClass):
    print("obj is an instance of MyClass")
else:
    print("obj is not an instance of MyClass")

You can also use the issubclass() function to check if a class is a subclass of another class, like this:

class MyParentClass:
    pass

class MyChildClass(MyParentClass):
    pass

if issubclass(MyChildClass, MyParentClass):
    print("MyChildClass is a subclass of MyParentClass")
else:
    print("MyChildClass is not a subclass of MyParentClass")