Finding the name of a class
Bruno Desthuilliers
onurb at xiludom.gro
Wed Aug 2 03:28:53 EDT 2006
Kirk Strauser wrote:
> 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,
Ok. Could have been a typo, just wanted to make sure.
>> 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. :-)
Not sure if it works for old-style classes...
> 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.im_class
<class '__main__.Foo'>
>>> b.im_class.__name__
'Foo'
>>>
>>>> b.__class__
This will give you the class of b itself. Remember that in Python,
everything and it's sister is an object - including functions, methods,
classes and modules.
In this case, b is a method object - IOW a descriptor that wraps a
function object.
--
bruno desthuilliers
python -c "print '@'.join(['.'.join([w[::-1] for w in p.split('.')]) for
p in 'onurb at xiludom.gro'.split('@')])"
More information about the Python-list
mailing list