Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Getting the class name of an instance?

How do I find out a name of class that created an instance of an object in Python if the function I am doing this from is the base class of which the class of the instance has been derived?

Was thinking maybe the inspect module might have helped me out here, but it doesn't seem to give me what I want. And short of parsing the __class__ member, I'm not sure how to get at this information.

like image 636
Dan Avatar asked Feb 04 '09 11:02

Dan


People also ask

What is the name for an instance of a class?

An instance of a class is an object. It is also known as a class object or class instance. As such, instantiation may be referred to as construction. Whenever values vary from one object to another, they are called instance variables.

How do I find the class name of an object?

If you have a JavaSW object, you can obtain it's class object by calling getClass() on the object. To determine a String representation of the name of the class, you can call getName() on the class.

How do I get an instance of a class in Python?

There are two ways to access the instance variable of class:Within the class by using self and object reference. Using getattr() method.


2 Answers

Have you tried the __name__ attribute of the class? ie type(x).__name__ will give you the name of the class, which I think is what you want.

>>> import itertools >>> x = itertools.count(0) >>> type(x).__name__ 'count' 

If you're still using Python 2, note that the above method works with new-style classes only (in Python 3+ all classes are "new-style" classes). Your code might use some old-style classes. The following works for both:

x.__class__.__name__ 
like image 180
sykora Avatar answered Sep 19 '22 15:09

sykora


Do you want the name of the class as a string?

instance.__class__.__name__ 
like image 27
mthurlin Avatar answered Sep 16 '22 15:09

mthurlin