How to get the Class Name of an Object in Python
Table of Contents
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:
PYTHONclass 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.
PYTHONprint(type(person).__name__)
BASHPerson
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:
PYTHONclass Person:
def __init__(self, name):
self.name = name
person = Person("John")
Let's now get the name of the class of the person
object:
PYTHONprint(person.__class__.__name__)
BASHPerson
__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!
- Getting Started with Solid
- Managing PHP Dependencies with Composer
- Getting Started with Svelte
- Git Tutorial: Learn how to use Version Control
- How to deploy a .NET app using Docker
- Best Visual Studio Code Extensions for 2022
- How to deploy a Node app using Docker
- Getting User Location using JavaScript's Geolocation API
- Learn how to build a Slack Bot using Node.js
- Creating a Twitter bot with Node.js
- Using Push.js to Display Web Browser Notifications
- Setting Up a Local Web Server using Node.js