AppDividend
Latest Code Tutorials

How to Get Class Name in Python

0

A python is an object-oriented programming language, and almost everything is an object, with its properties and methods. In Python, use the type(object) function to return a type object. To access the classname of the type of the object, use the __name__ attribute.

A Class in Python is like an object constructor or a “blueprint” for creating objects.

Get Class Name in Python

To get the class name of an instance in Python, use one of the following ways.

  1. Using the combination of type() Function and __name__ to get the type or class of the Object/Instance.
  2. Using the combination of the __class__ and __name__ to get the type or class of the Object/Instance.

The type() function is used to get the data type of the Python object.

Example

Let’s take a simple example of string and check out its class name.

data = "Playstation 5"

print(type(data).__name__)

Output

str

As you can see that the class of string instance is str.

Let’s use the itertools module and use its repeat instance and get its class name.

import itertools

data = itertools.repeat(1)

print(type(data).__name__)

Output

repeat

Let’s define an empty list and find the class of the list instance.

a_list = []

data_type = type(a_list)

class_name = data_type.__name__

print(class_name)

Output

list

If you are using Python 2.x, then the following syntax will work for you.

data.__class__.__name__

You can also get the name of the class as a string.

class K:
    pass


k = K()
print(str(k.__class__))

Output

<class '__main__.K'>

That’s it for this tutorial.

 

Leave A Reply

Your email address will not be published.

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