Finding the name of a class

Bruno Desthuilliers onurb at xiludom.gro
Tue Aug 1 11:37:26 EDT 2006


Kirk Strauser wrote:
> Given a class:
> 
>>>> class foo(object):
>>>>     pass
> 
> how can I find its name, such as:
> 
>>>> b = foo

I suppose you mean b = foo() ?

>>>> print something(b)
> 'foo'

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.

>>> class Foo(object):
...     pass
...
>>> b = Foo
>>> b.__name__
'Foo'
>>> b = Foo()
>>> b.__class__.__name__
'Foo'
>>>

> I'm writing a trace() decorator for the sake of practice, and am trying to
> print the name of the class that a traced method belongs to.  This seems
> like it should be easy, but I think I've been staring at the problem too
> long.

>>> help(dir)
Help on built-in function dir in module __builtin__:

dir(...)
    dir([object]) -> list of strings

    Return an alphabetized list of names comprising (some of) the attributes
    of the given object, and of attributes reachable from it:

    No argument:  the names in the current scope.
    Module object:  the module attributes.
    Type or class object:  its attributes, and recursively the attributes of
        its bases.
    Otherwise:  its attributes, its class's attributes, and recursively the
        attributes of its class's base classes.

>>>

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