Finding the name of a class

Bruno Desthuilliers onurb at xiludom.gro
Wed Aug 2 03:35:16 EDT 2006


Dennis Lee Bieber wrote:
> On Tue, 01 Aug 2006 11:09:57 -0500, Kirk Strauser <kirk at strauser.com>
> declaimed the following in comp.lang.python:
> 
>> 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).
>>
> 	Pardon... That gives the class object another name, neither of which
> has any precedence over the other.

Not quite exactly. The 'b = foo' statement binds together name b and the
object foo - which in this case happens to be a class. OTOH, class
objects do have a __name__ attribute, which is not impacted by the binding.

>>>>> 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'.
> 
> 	But... you've just pulled the method "out" of the class
> definition... Without supplying an instance, there is no linkage to a
> class.

Yes there is. Method objects have an im_class attribute, that is a
reference to the class they were 'pulled out' from.


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