Get class name from within a class in Python

avatar

Borislav Hadzhiev

Last updated: Sep 13, 2022

banner

Photo from Unsplash

Get class name from within a class in Python #

Use a class method to get a class's name from within the class. Class methods get passed the class as the first argument and you can access the name of the class as cls.__name__.

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.

The __name__ attribute returns the name of 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.

We used the type() class to get access to the class inside of the example method.

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.

Using the __class__ attribute on the self object would have achieved the same result.

main.py
def example(self): print(self.__class__.class_name)

You can also access the class's name via the __name__ attribute inside of a class method.

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

The __name__ attribute can also be used if you need to access the class's name from outside the class.

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

If you only have access to an instance, use the type() class before accessing the __name__ attribute.

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.