How to Get the Class Name of a Python Object?

Find out how to get an object's class name in Python

In Python, you can get an object's class name by accessing the special __name__ attribute on the return value of the built-in type() function (or the __class__ attribute):


# is equivalent to:

Generally, calling special attributes (i.e. those starting and ending with double underscores) directly is discouraged. Therefore, you should use the type() function instead of __class__ wherever possible. However, same is not true for __name__ as there's no function alternative for it.

For example, you can check the class name for a string like so:

name = "John Doe"

print(type(name).__name__) # "str"
print(name.__class__.__name__) # "str"

Similarly, for a list, you can check the class name like so:

numbers = [1, 2, 3, 4]

print(type(numbers).__name__) # "list"
print(numbers.__class__.__name__) # "list"

If you have a custom class, you can check the class name of its object instance like so:

class Person:
   def __init__(self, name, age): = name
      self.age = age

person = Person("John Doe", 39)

print(type(person).__name__) # "Person"
print(person.__class__.__name__) # "Person"

Hope you found this post useful. It was published . Please show your love and support by sharing this post.