W3docs

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.

To get the class name of an instance in Python, you can use the __class__ attribute of the object. For example:

Getting the class name of an instance in Python using the class method

class MyClass:
    pass

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

<div class="alert alert-info flex not-prose"> Watch a course <span class="hidden md:block">Watch a video course </span> Python - The Practical Guide</div>

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:

Getting the class name of an instance in Python using the type function

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:

Define a function that gets the class name of an instance in Python

class MyClass:
    pass

obj = MyClass()

def classname(obj):
    return obj.__class__.__name__

class_name = classname(obj)
print(class_name)  # Output: "MyClass"