How to get the parents of a Python class?

后端 未结 6 1834
野趣味
野趣味 2020-11-28 03:49

How can I get the parent class(es) of a Python class?

6条回答
  •  囚心锁ツ
    2020-11-28 04:40

    The FASTEST way, to see all parents, and IN ORDER, just use the built in __mro__

    i.e. repr(YOUR_CLASS.__mro__)


    >>>
    >>>
    >>> import getpass
    >>> getpass.GetPassWarning.__mro__
    

    outputs, IN ORDER


    (, ,
    , , 
    , )
    >>>
    

    There you have it. The "best" answer right now, has 182 votes (as I am typing this) but this is SO much simpler than some convoluted for loop, looking into bases one class at a time, not to mention when a class extends TWO or more parent classes. Importing and using inspect just clouds the scope unnecessarily. It honestly is a shame people don't know to just use the built-ins

    I Hope this Helps!

提交回复
热议问题