List all base classes in a hierarchy of given class?
See the __bases__
property available on a python class
, which contains a tuple of the bases classes:
>>> def classlookup(cls):
... c = list(cls.__bases__)
... for base in c:
... c.extend(classlookup(base))
... return c
...
>>> class A: pass
...
>>> class B(A): pass
...
>>> class C(object, B): pass
...
>>> classlookup(C)
[<type 'object'>, <class __main__.B at 0x00AB7300>, <class __main__.A at 0x00A6D630>]
inspect.getmro(cls)
works for both new and old style classes and returns the same as NewClass.mro()
: a list of the class and all its ancestor classes, in the order used for method resolution.
>>> class A(object):
>>> pass
>>>
>>> class B(A):
>>> pass
>>>
>>> import inspect
>>> inspect.getmro(B)
(<class '__main__.B'>, <class '__main__.A'>, <type 'object'>)
inspect.getclasstree()
will create a nested list of classes and their bases.
Usage:
inspect.getclasstree(inspect.getmro(IOError)) # Insert your Class instead of IOError.