How to get the Class Name of an Object in Python

Updated onbyAlan Morel
How to get the Class Name of an Object in Python

Because Python is an object-oriented programming language, everything in Python is an object, with its properties and methods.

Once you have an object, it might be useful to know the name of the class it belongs to. This is especially useful when you are working with a third-party library and you want to know the class of an object.

In this article, we will learn how to get the name of the class of an object in Python.

How to get the name of the class of an object in Python using type()

To learn how to get the name of the class of an object in Python, we will use the following example:

PYTHON
class Person: def __init__(self, name): self.name = name person = Person("John")

In this example, we have a class called Person and an object called person.

The Person class takes in a name and stores it in the name attribute.

To get the name of the class of an object, we can use the type() function, then get the __name__ attribute of the returned object.

PYTHON
print(type(person).__name__)
BASH
Person

type() is a built-in function that returns the type of an object, and the __name__ attribute is the name of the class.

How to get the name of the class of an object in Python using class

Another way to get the name of the class of an object in Python is to use the __class__ attribute of the object.

Let's again use the previous example to see how this works:

PYTHON
class Person: def __init__(self, name): self.name = name person = Person("John")

Let's now get the name of the class of the person object:

PYTHON
print(person.__class__.__name__)
BASH
Person

__class__ is an attribute of the object that returns the class of the object, then like with before, we can then get the __name__ attribute of the returned object.

Conclusion

In this post, we learned how to get the name of the class of an object in Python.

Simply use the type() function, then get the __name__ attribute of the returned object, or use the __class__ attribute of the object, then get the __name__ attribute of the returned object.

Thanks for reading!

To learn more about web development, founding a start-up, and bootstrapping a SaaS, follow me on X!
Copyright © 2017 - 2024 Sabe.io. All rights reserved. Made with ❤ in NY.