You can dynamically get the class name of a Python object using the following methods:
Method 1: Using the __class__ Attribute
obj = My Class()
class_name = obj.class – name__
print(class_name) – Output: My Class
Method 2: Using the type
obj = MyClass()
class_name = type(obj).__name__
print(class_name) # Output: MyClass
Both methods will give you the class name as a string.
Example Use Case
class Person:
def __init__(self, name):
self.name = name
person = Person(“John”)
print (person class -name__) – Output: Person
Note
In Python 3.x, __class__ is the recommended way to get the class of an object. In Python 2.x, type() is more reliable. However, in most cases, both methods will work as expected.