How to get the parents of a Python class?

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

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

6条回答
  •  鱼传尺愫
    2020-11-28 04:36

    Use bases if you just want to get the parents, use __mro__ (as pointed out by @naught101) for getting the method resolution order (so to know in which order the init's were executed).

    Bases (and first getting the class for an existing object):

    >>> some_object = "some_text"
    >>> some_object.__class__.__bases__
    (object,)
    

    For mro in recent Python versions:

    >>> some_object = "some_text"
    >>> some_object.__class__.__mro__
    (str, object)
    

    Obviously, when you already have a class definition, you can just call __mro__ on that directly:

    >>> class A(): pass
    >>> A.__mro__
    (__main__.A, object)
    

提交回复
热议问题