Python get class name : Use the type() Function and __name__ and Use the __class__ and __name__ Properties to Get the Type or Class of an Object/Instance.
I will learn different ways to get the class name of the given instance in Python.
Python Program to Get the Class Name of an Instance. Write a Python class to get the class name of an instance in Python.
Getting the class name of an instance
>>> import itertools
>>> x = itertools.count(0)
>>> type(x).__name__
'count'
Example
Use the type() Function and __name__ to Get the Type or Class of the Object/Instance
class active:
def __init__(self, active):
self.active = active
x = active(1)
print (type(x).__name__)
Result:
active
Example 2
Use the __class__ and __name__ Properties to Get the Type or Class of an Object/Instance
class active:
def __init__(self, active):
self.active = active
x = active(1)
print (x.__class__)
print (x.__class__.__name__)
Results
<class '__main__.active'>
active
Using __class__.__name__
class Website:
def name(self, name):
return name
w = Website()
print(w.__class__.__name__)
output
Website
Using type() and __name__ attribute
class Website:
def name(self, name):
return name
w = Website()
print(type(w).__name__)
output
Website
python get class name
demos/other/class.py
import re
first = 8
second = "4"
third = 9.6
m = re.search(r'\d', str(third))
print(first.__class__)
print(second.__class__)
print(third.__class__)
print(type(first))
print(type(second))
print(type(third))
print(first.__class__.__name__)
print(second.__class__.__name__)
print(third.__class__.__name__)
print(re.__class__.__name__)
print(m.__class__.__name__)
I hope you get an idea about python get class name.