Get Class Name in Python

Get Class Name in Python

  1. Use the type() Function and __name__ to Get the Type or Class of the Object/Instance
  2. Use the __class__ and __name__ Properties to Get the Type or Class of an Object/Instance

A class, just like an object constructor, can be defined as a user-defined prototype that is used to create objects. Classes can be created using the keyword class.

A class is a data structure, and it can hold both data members and member methods.

This tutorial will discuss the method to get the class name in Python.

Use the type() Function and __name__ to Get the Type or Class of the Object/Instance

type() is a predefined function that can be used in finding the type or class of an object.

__name__ is a special built-in variable that basically gives the name of the current module where it is used. Since python has no main() function like the other languages like C/C++, Java, and other similar languages, if it is the source file that is executed as the main program, then the interpreter sets the value of __main__ to __name__. At the same time, when a file is imported from any other module, __name__ is then set to that module’s name.

The type() function and the __name__ variable are used to get the type or class of the object in the following code.

class num:
    def __init__(self, num):
        self.num = num
x = num(1)
print (type(x).__name__)

Output:

num

In Python 3, all created classes are new-style classes, while in Python 2, old-style classes might co-exist with the new-style classes. A new-style class is a class that gets inherited from the instance of the object, while old-style or classic classes are the basic classes that existed before python 2.1.

The above method can work only with new-style classes.

Use the __class__ and __name__ Properties to Get the Type or Class of an Object/Instance

The __class__ property can also be used to find the class or type of an object. It basically refers to the class the object was created in.

The __name__ can also be used along with __class__ to get the class of the object.

The following code uses both __class__ and __name__ to get the class of an object.

class num:
    def __init__(self, num):
        self.num = num
x = num(1)
print (x.__class__)
print (x.__class__.__name__)

Output:

<class '__main__.num'>
num

Related Article - Python Class

  • Python Generator Class
  • Data Class Inheritance in Python
  • Serialize a Python Class Object to JSON
  • Python Abstract Property
  • Python Class Factory
  • Python Class Equality