Get class name as string in Python

To get class name as a string in Python, there are three possible methods: using `class.__name__`, using`type()` with the `name` attribute, and using `__class__.__qualname__` for nested classes. These methods facilitate class name retrieval for debugging, logging, or dynamic class instantiation needs.

Python is a versatile and powerful programming language that offers various tools to manipulate data and objects. One common task in Python is to retrieve the name of a class as a string. Knowing the class name as a string can be helpful in scenarios like debugging, logging, or dynamic class instantiation. In this blog, we'll explore different methods to obtain the class name as a string with example codes and detailed explanations.

code, programming, python

Python get class name as string using class.__name__ 

In Python, every class is derived from the object class. The class attribute is a reference to the class from which an object is created. We can use this attribute to retrieve the class name as a string using the name attribute. Let's understand this in detail using following example:

Example:

class Dog:

def init(self, name):

     self.name = name

def get_class_name(self): # current module class Dog

     return self.__class__.__name__

# Create an instance of the Dog class

dog_instance = Dog("Buddy")

# Get the class name as a string

class_name = dog_instance.get_class_name()

# Output the result

print("Class Name:", class_name)  # Output: Class Name: Dog

In this example, we defined a simple class called "Dog" with an instance method get_class_name(). Inside this method, we use self.__class__.__name__ to retrieve the class name as a string. When we create an instance of the Dog class and call the get_class_name() method on it, the output will be: Class Name: Dog

Python get class name as string using type() and name attribute

Another method to obtain the class name as a string is by using the type() function along with the name attribute. The type() function returns the type of an object, which in this case, is our class. The name attribute then provides the class name as a string. Let's understand this in detail using following code:

Example:

class Cat:

def init(self, name):

     self.name = name

# Create an instance of the Cat class

cat_instance = Cat("Whiskers")

# Get the class name as a string using type() and name

class_name = type(cat_instance).__name__

# Output the result

print("Class Name:", class_name)  # Output: Class Name: Cat

In this example, we defined a class "Cat" and created an instance named "cat_instance." Using type(cat_instance).__name__, we retrieve the class name as a string.

Python get class name as string using nested classes

Python allows us to define classes within other classes, known as nested classes. When dealing with nested classes, we can use the qualname attribute to obtain the fully-qualified name of the class as a string. The fully-qualified name includes the names of all enclosing classes, separated by dots. Let's understand this using below example:

Example:

class Car:

def init(self, make):

     self.make = make

class Engine:

     def init(self, horsepower):

         self.horsepower = horsepower

# Create an instance of the nested class Engine

engine_instance = Car.Engine(horsepower=200) # engine_instance is a name of an instance

# Get the fully-qualified class name as a string using qualname

class_name = engine_instance.__class__.__qualname__

# Output the result

print("Class Name:", class_name)  # Output: Class Name: Car.Engine

In this example, we have a class "Car" containing a nested class "Engine." We create an instance of the Engine class and use engine_instance.__class__.__qualname__ to obtain the fully-qualified class name.

Conclusion

In this blog post, we explored three various methods to get the class name as a string in Python. The first method - class.__name__ provided a direct and simple approach, perfect for most scenarios. The second method, using type() and name, offered an alternative way to achieve the same result. Lastly, we delved into dealing with two classes (nested) and how the qualname attribute can give us the python class fully-qualified object name. 

Understanding these techniques will empower you to work effectively with class names in your Python projects.

You can also check these blogs:

  1. How to remove multiple items from a Python list?
  2. Jaccard similarity in Python
  3. Python JSON Validator
  4. rstrip vs strip in Python: Trimming whitespaces made easy
  5. Master String Trimming in Python
  6. Python t-Test Simplified
  7. Converting Lists to Sets in Python
  8. Dataframe to List in Python
  9. File Renaming in Python
  10. How to make a directory in Python if it does not exist?