Finding the name of a class

Kirk Strauser kirk at strauser.com
Tue Aug 1 12:09:57 EDT 2006


Bruno Desthuilliers wrote:

> Kirk Strauser wrote:

>>>>> class foo(object):
>>>>>     pass
>> 
>> how can I find its name, such as:
>> 
>>>>> b = foo

> I suppose you mean b = foo() ?

Actually, I meant 'b = foo' in this case - I want to find the name of the
class that b references, but the name of an instance (which may have zero
or many references to it).

> The name of a class is in the attribute '__name__' of the class. The
> class of an object is in the attribute '__class__' of the object.

I swear that didn't work earlier.  Honest.  :-)

OK, now for the good stuff.  In the code below, how can I find the name of
the class that 'bar' belongs to:

>>> class Foo(object):
...     def bar(self):
...             pass
...
>>> b = Foo.bar
>>> dir(b)
['__call__', '__class__', '__cmp__', '__delattr__', '__doc__', '__get__', '__getattribute__', '__hash__', '__init__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__setattr__', '__str__', 'im_class', 'im_func', 'im_self']
>>> b.__class__
<type 'instancemethod'>
>>> b.__class__.__name__
'instancemethod'

I was sort of hoping that it would print 'Foo'.
-- 
Kirk Strauser



More information about the Python-list mailing list