List all base classes in a hierarchy of given class?

后端 未结 7 983
清歌不尽
清歌不尽 2020-11-28 02:28

Given a class Foo (whether it is a new-style class or not), how do you generate all the base classes - anywhere in the inheritance hierarchy -

相关标签:
7条回答
  • 2020-11-28 02:59

    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>]
    
    0 讨论(0)
提交回复
热议问题