Get the Class Name of an object in Python

avatar

Borislav Hadzhiev

Last updated: Sep 13, 2022

banner

Photo from Unsplash

Get the Class Name of an object in Python #

To get the class name of an object:

  1. Pass the instance to the type() class to get access to the class.
  2. Access the __name__ attribute on the class.
  3. The __name__ attribute will return the class name of the object.
main.py
class Employee(): pass result = Employee.__name__ print(result) # 👉️ Employee emp1 = Employee() result = type(emp1).__name__ print(result) # 👉️ Employe

We used the __name__ attribute to get the class name of an object.

The __name__ attribute returns the name of the class.

If you have access to the class, you can directly access the attribute on the class.

If you only have access to an instance of the class, use the type() class to get access to the class before accessing the __name__ attribute.
main.py
class Employee(): pass emp1 = Employee() result = type(emp1).__name__ print(result) # 👉️ Employe

The type class returns the type of an object.

Most commonly the return value is the same as accessing the __class__ attribute on the object.
main.py
class Employee(): pass emp1 = Employee() result = emp1.__class__.__name__ print(result) # 👉️ Employe

You can use the same approach to access the name of the class from within a method.

main.py
class Employee(): def print_class_name(self): print(type(self).__name__) emp1 = Employee() emp1.print_class_name() # 👉️ Employee

You can use a class method to access the class's name from within the class.

main.py
class Employee(): @classmethod def get_class_name(cls): return cls.__name__ print(Employee.get_class_name()) # 👉️ Employee

We marked the get_class_name method as a class method. The first argument class methods get passed is the class.

Alternatively, you can use the __qualname__ attribute.

main.py
class Employee(): class_name = __qualname__ @classmethod def get_class_name(cls): print(cls.class_name) return cls.__name__ def example(self): print(type(self).class_name) print(Employee.get_class_name()) # 👉️ Employee emp1 = Employee() emp1.example() # 👉️ Employee

The __qualname__ attribute returns the qualified name of the class.

I wrote a book in which I share everything I know about how to become a better, more efficient programmer.
book cover
You can use the search field on my Home Page to filter through all of my articles.