get classname of instance in python

How to Get Classname of Instance in Python

Often you may need to get the classname of a given python object instance. In this article, we will learn several ways to get classname of instance in python.


How to Get Classname of Instance in Python

Every instance object has an attribute __class__ that contains a variable which contains the class of object. It further contains an attribute __name__ which contains name of the class.

# this is a class named abc
class abc:
	def parts():
		pass

c = abc()

# this prints the class of a c
# this is a class of a c which is
# variable containing a class
print(c.__class__)

# this prints the name of the class
classes = c.__class__
print(classes.__name__)

Here is the output you will see.

<class '__main__.abc'>
abc

You can also use type() function on the instance, to get the type class, and then call __name__ attribute.

# this is a class named abc
class abc:
	def parts():
		pass

c = abc()

# this prints the class of a c
print(type(c).__name__)

In this article, we have learnt a couple of simple ways to get classname of instance in python.

Also read:

How to Lock File in Python
How to Use Boolean Variables in Shell
How to Concatenate Strings in Shell Script
How to Iterate Over Arguments in Shell Script
Bash Script That Takes Optional Arguments

Leave a Reply

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