List all base classes in a hierarchy of given class?

后端 未结 7 1048
清歌不尽
清歌不尽 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:36

    According to the Python doc, we can also simply use class.__mro__ attribute or class.mro() method:

    >>> class A:
    ...     pass
    ... 
    >>> class B(A):
    ...     pass
    ... 
    >>> B.__mro__
    (, , )
    >>> A.__mro__
    (, )
    >>> object.__mro__
    (,)
    >>>
    >>> B.mro()
    [, , ]
    >>> A.mro()
    [, ]
    >>> object.mro()
    []
    >>> A in B.mro()
    True
    
    

提交回复
热议问题