Categories
Python Answers

How to get the class name of an instance with Python?

Spread the love

Sometimes, we want to get the class name of an instance with Python.

In this article, we’ll look at how to get the class name of an instance with Python.

How to get the class name of an instance with Python?

To get the class name of an instance with Python, we can use the type function and the __name__ property.

For instance, we write:

class A:
    def whoami(self):
        print(type(self).__name__)


a = A()
a.whoami()

We create the A class with the whoami method that prints the class name by printing type(self).__name__.

Therefore, we should see 'A' printed when we create a new A instance and assign it to a and then call a.whoami.

Conclusion

To get the class name of an instance with Python, we can use the type function and the __name__ property.

By John Au-Yeung

Web developer specializing in React, Vue, and front end development.

Leave a Reply

Your email address will not be published. Required fields are marked *