How To Get Class Name In Python?

Python Class is used to define different and custom data structures with variables and methods. We can create single or multiple classes with different names. The class name is used to define a class uniquely. Also, the class name is used to initialize an object. In some cases, we may need to get the class name of the object or instance. There are different ways to get the class names in Python. We examine these methods in detail for this tutorial.

Get Class Name Using __class__.__name__ Attribute

The first and most practical way to get a class name is using the objects __class__.__name__ attribute of the object. In the following example, we create an instance and get its name by using the “__class__.__name__”.

class Person:
   name="İsmail Baydan"

p = Person()

print(p.__class__.__name__)

Get Class Name Using type() Function and __name__ Attribute

Python provides the type() function in order to return the type of the specified object. This object type provides the __name__ attribute which provides the name of the class.

class Person:
   name="İsmail Baydan"

p = Person()

print(type(p).__name__)

Get Class Name For Nested Classes

Python supports nested classes where a class contains another class. We can get the nested classes and all class names by using the __class__.__qualname__ attribute.

class Person:
   name="İsmail Baydan"
   def __init__(self):
      self.citizen=self.Citizen()
   class Citizen:
      country="Turkey"

p = Person()

print(p.__name__)

print(p.citizen.__name__)
Person
Person.Citizen

Leave a Comment