Find the class name from the instance

Asked 1 years ago, Updated 1 years ago, 95 views

Is there a way to find out the class name of the instance in Python? I thought I could use the inspect module, but I couldn't find it.

python introspection instanceof pythondatamodel

2022-09-22 14:49

1 Answers

Write _name__. __name__ stores the name of the class/type.

#class for example
class myClassName(object):
    pass
x = myClassName()

when you say you're with You want to find out "myClassName" through instance x right?

#For new style - type(x).Use __name__
print "----for new style---"
print "x:\t\t\t\t\t", x
print "type(x):\t\t\t", type(x)
print "type(x).__name__:\t",type(x).__name__

If #oldstyle - x.__class__.Use __name__
print"\n---for old style---"
print "x.__class__.__name__:", x.__class__.__name__```

Results)

----for new style---
x:                  <__main__.myClassName object at 0x10171c710>
type(x):            <class '__main__.myClassName'>
type(x).__name__:   myClassName

---for old style---
x.__class__.__name__: myClassName


2022-09-22 14:49

If you have any answers or tips


© 2024 OneMinuteCode. All rights reserved.