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?
相关问题
- how to define constructor for Python's new Nam
- streaming md5sum of contents of a large remote tar
- How to get the background from multiple images by
- Evil ctypes hack in python
- Correctly parse PDF paragraphs with Python
inspect.getmro(cls)
works for both new and old style classes and returns the same asNewClass.mro()
: a list of the class and all its ancestor classes, in the order used for method resolution.you can use the
__bases__
tuple of the class object:The tuple returned by
__bases__
has all its base classes.Hope it helps!
attention that in python 3.x every class inherits from base object class.
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:
An inheriting class
ex:
An inherited class
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
will show you the hierarchy, within Python.
inspect.getclasstree()
will create a nested list of classes and their bases. Usage:According to the Python doc, we can also simply use
class.__mro__
attribute orclass.mro()
method: