views:

6855

answers:

3

Hi,

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 inspects 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.

Thanks Dan

+2  A: 

type() ?

>>> class A(object):
...    def whoami(self):
...       print type(self).__name__
...
>>>
>>> class B(A):
...    pass
...
>>>
>>>
>>> o = B()
>>> o.whoami()
'B'
>>>
GHZ
this is the same as the __class__ member, but i have to parse this result by hand, which is a bit annoying...
Dan
+23  A: 

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

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

It should work similarly from wherever you call it.

sykora
+9  A: 

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

instance.__class__.__name__
truppo