Python get Class name as String examples
This tutorial covers the following topics in Python:
- How to get Concrete class name as a string
- find the full qualified name of an instance of an object class
Getting the Class Name as a String
Use the __name__
attribute to retrieve the class name using an instance object. The __name__
attribute returns the class name of an instance of a class.
In Python 3, you can use name on the result of the type function with an object.
class Employee:
pass
e= Employee()
print(type(e).__name__)# Employee
In Python 2.x, you can use instance.__class__.__name__
to get the class name.
class Employee:
pass
e= Employee()
print(e.__class__.__name__)# Employee
Python Decorator to Get the Class Name of a Class
Declare a class method with the @classmethod
decorator. The method takes an instance and returns the nam`e attribute.
Create an instance of a class and call the function to get the class name as a string.
class Employee:
@classmethod
def classname(self):
return self.__name__
e= Employee()
print(e.classname()) # Employee
Getting the Qualified Name of a Class Instance
The qualname attribute returns the qualified name of a class, providing a nested class hierarchy of class names.
Here is an example
class Employee:
class AdminEmployee:
def func(self):
pass
e= Employee.AdminEmployee()
print(type(e).__name__) # AdminEmployee
print(type(e).__qualname__) # Employee.AdminEmployee