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!
How to Set Up Cron Jobs in Linux
Best Visual Studio Code Extensions for 2022
Getting Started with Deno
How to deploy an Express app using Docker
Learn how to use v-model with a custom Vue component
How to Scrape the Web using Node.js and Puppeteer
Getting Started with Handlebars.js
Getting User Location using JavaScript's Geolocation API
Using Push.js to Display Web Browser Notifications
Building a Real-Time Note-Taking App with Vue and Firebase
Getting Started with Vuex: Managing State in Vue
Using Axios to Pull Data from a REST API
