Friday, January 17, 2025
HomeGeneralHow can I dynamically get the class name of a Python Object?

How can I dynamically get the class name of a Python Object?

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

See also  90+True Love Quotes to Appreciate Love

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.

RELATED ARTICLES
0 0 votes
Article Rating

Leave a Reply

0 Comments
Oldest
Newest Most Voted
Inline Feedbacks
View all comments
- Advertisment -

Most Popular

Recent Comments

0
Would love your thoughts, please comment.x
()
x