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 TypeScript
- How to Install Node on Windows, macOS and Linux
- Create an RSS Reader in Node
- How to Set Up Cron Jobs in Linux
- How to deploy a .NET app using Docker
- How to build a Discord bot using TypeScript
- How to deploy a Deno app using Docker
- Getting Started with Deno
- Getting Started with Sass
- Getting User Location using JavaScript's Geolocation API
- Building a Real-Time Note-Taking App with Vue and Firebase
- Setting Up Stylus CSS Preprocessor