How to list the superclassesof an object

Alex Martelli aleax at aleax.it
Wed Nov 5 11:17:11 EST 2003


Fernando Rodriguez wrote:

> Hi,
> 
> How can I list the superclasses of an object? O:-)

>>> class A: pass
...
>>> class B: pass
...
>>> class C(A,B): pass
...
>>> x=C()
>>> x.__class__.__bases__
(<class __main__.A at 0x402db41c>, <class __main__.B at 0x402db44c>)


You may need a recursive walk up the (DA) graph if you also want
bases of bases, etc, among 'superclasses'; alternatively, but
ONLY for newstyle classes (recommended anyway for many reasons):

>>> class C(object, A, B): pass
...
>>> x = C()
>>> x.__class__.__mro__
(<class '__main__.C'>, <type 'object'>, <class __main__.A at 0x402db41c>,
<class __main__.B at 0x402db44c>)
>>>

the __mro__ attribute of a newstyle class does the walk on your
behalf, in the right order, removing duplicates, etc, etc...


Alex





More information about the Python-list mailing list