How to find the classname of an object? (was Python Documentation)
Bengt Richter
bokr at oz.net
Thu May 12 21:11:11 EDT 2005
On Thu, 12 May 2005 23:30:21 GMT, Farshid Lashkari <lashkariNO at SPAMworldviz.com> wrote:
>This will get the name of an objects class
>
>obj.__class__.__name__
>
>This will return a tuple of its base classes
>
>obj.__class__.__bases__
But not all base classes that it inherits from, e.g.,
>>> class C(object): pass
...
>>> class B1(C): pass
...
>>> class B2(C): pass
...
>>> class A(B1, B2): pass
...
>>> obj = A()
>>> obj.__class__.__name__
'A'
>>> obj.__class__.__bases__
(<class '__main__.B1'>, <class '__main__.B2'>)
>>> type(obj)
<class '__main__.A'>
>>> type(obj).mro()
[<class '__main__.A'>, <class '__main__.B1'>, <class '__main__.B2'>, <class '__main__.C'>, <type 'object'>]
>>> tuple(x.__name__ for x in type(obj).mro())
('A', 'B1', 'B2', 'C', 'object')
>
>Christopher J. Bottaro wrote:
>> I actually want all the parent classes too. So if D derives off C derives
>> off B derives off A, I ultimately want a tuple ('D', 'C', 'B', 'A').
>>
>> For those of you following the Python Documentation thread, this is a good
>> example of how the PHP manual is "better". I found how to do this in a few
>> seconds in PHP. I searched the Python docs for "class name", "classname",
>> "introspection" and "getclass". I looked in the Class section of the
>> tutorial also and also the Programming FAQ. The "related functions"
>> section of the PHP manual is really helpful. It would be cool if in the
>> section for the built-in function isinstance() or issubclass() there is a
>> section for "related functions" that would point me to getclassname(obj)
>> (if it exists).
>>
>> Thanks for the help.
>>
>> -- C
>>
Regards,
Bengt Richter
More information about the Python-list
mailing list