How to Get the Class Name of an Instance in Python

Here are three ways to get the class name of an instance in Python.

  1. Using .__class__.__name__ Attribute
  2. Using the type() function
  3. Using __qualname__ attribute

Method 1: Using .__class__.__name__ Attribute

This is the most straightforward way to get the name of a class by using the __class__ attribute in combination with the __name__ attribute.

Example

class Country:
 pass

# Create an instance of Country
my_country = Country()

# Get the class name from the instance
class_name_from_instance = my_country.__class__.__name__

print(my_country.__class__)
print("Class name (from instance):", class_name_from_instance)

# Get the class name directly from the class
# class_name_from_class = Country.__name__
# print("Class name (from class):", class_name_from_class)

Output

<class '__main__.Country'>
Class name (from instance): Country

Method 2: Use the type() function

You can use the built-in type() function, which returns the class of the instance, and then access the class’s __name__ attribute to get the class name as a string.

Example

class Country:
 pass

# Create an instance of Country
my_country = Country()

# using type()
class_name_from_instance = type(my_country).__name__

print(my_country.__class__)
print("Class name (from instance):", class_name_from_instance)

Output

<class '__main__.Country'>
Class name (from instance): Country

Method 3: Using __qualname__ attribute

You can use the __qualname__ attribute when dealing with nested classes, as it provides the fully qualified name of a class. This includes the names of any enclosing classes.

Example

class Country:

 def __init__(self, name, cities):
 self.name = name
 self.major_cities = self.Cities(cities)

 class Cities:
 def __init__(self, city_list):
 self.city_list = city_list

country = Country("US", ['New York', 'Las Vegas'])

print(country.major_cities.__class__.__name__)    # the name of the nested class
print(country.major_cities.__class__.__qualname__) # the qualified name of the nested class

Output

Cities
Country.Cities

Leave a Comment

This site uses Akismet to reduce spam. Learn how your comment data is processed.