List all base classes in a hierarchy of given clas

2020-01-25 03:30发布

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 - it issubclass of?

7条回答
SAY GOODBYE
2楼-- · 2020-01-25 04:07

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'>)
查看更多
来,给爷笑一个
3楼-- · 2020-01-25 04:07

you can use the __bases__ tuple of the class object:

class A(object, B, C):
    def __init__(self):
       pass
print A.__bases__

The tuple returned by __bases__ has all its base classes.

Hope it helps!

查看更多
The star\"
4楼-- · 2020-01-25 04:08

In python 3.7 you don't need to import inspect, type.mro will give you the result.

>>> class A:
...   pass
... 
>>> class B(A):
...   pass
... 
>>> type.mro(B)
[<class '__main__.B'>, <class '__main__.A'>, <class 'object'>]
>>>

attention that in python 3.x every class inherits from base object class.

查看更多
叼着烟拽天下
5楼-- · 2020-01-25 04:13

Although Jochen's answer is very helpful and correct, as you can obtain the class hierarchy using the .getmro() method of the inspect module, it's also important to highlight that Python's inheritance hierarchy is as follows:

ex:

class MyClass(YourClass):

An inheriting class

  • Child class
  • Derived class
  • Subclass

ex:

class YourClass(Object):

An inherited class

  • Parent class
  • Base class
  • Superclass

One class can inherit from another - The class' attributed are inherited - in particular, its methods are inherited - this means that instances of an inheriting (child) class can access attributed of the inherited (parent) class

instance -> class -> then inherited classes

using

import inspect
inspect.getmro(MyClass)

will show you the hierarchy, within Python.

查看更多
何必那么认真
6楼-- · 2020-01-25 04:24

inspect.getclasstree() will create a nested list of classes and their bases. Usage:

inspect.getclasstree(inspect.getmro(IOError)) # Insert your Class instead of IOError.
查看更多
做个烂人
7楼-- · 2020-01-25 04:24

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__
(<class '__main__.B'>, <class '__main__.A'>, <class 'object'>)
>>> A.__mro__
(<class '__main__.A'>, <class 'object'>)
>>> object.__mro__
(<class 'object'>,)
>>>
>>> B.mro()
[<class '__main__.B'>, <class '__main__.A'>, <class 'object'>]
>>> A.mro()
[<class '__main__.A'>, <class 'object'>]
>>> object.mro()
[<class 'object'>]
>>> A in B.mro()
True

查看更多
登录 后发表回答