How do I inspect a Python's class hierarchy?
Asked Answered
O

5

11

Assuming I have a class X, how do I check which is the base class/classes, and their base class/classes etc?

I'm using Eclipse with PyDev, and for Java for example you could type CTRL + T on a class' name and see the hierarchy, like:

java.lang.Object
   java.lang.Number
       java.lang.Integer

Is it possible for Python?

If not possible in Eclipse PyDev, where can I find this information?

Orbiculate answered 20/11, 2011 at 16:35 Comment(1)
This is answered in Python: List all base classes in a hierarchyHoney
H
8

Hit f4 with class name highlighted to open hierarchy view.

Hagai answered 20/11, 2011 at 16:42 Comment(0)
S
8

Try inspect.getclasstree().

Arrange the given list of classes into a hierarchy of nested lists. Where a nested list appears, it contains classes derived from the class whose entry immediately precedes the list. Each entry is a 2-tuple containing a class and a tuple of its base classes. If the unique argument is true, exactly one entry appears in the returned structure for each class in the given list. Otherwise, classes using multiple inheritance and their descendants will appear multiple times.

Sabbat answered 20/11, 2011 at 16:43 Comment(0)
B
7

Also, every class carries around with it an attribute called __mro__ which gives all the parent classes from which a given class could inherit methods or attributes. Read them from left to right. For example:

assert bool.__mro__ == (<class 'bool'>, <class 'int'>, <class 'object'>)
assert True.__class__.__mro__ == (<class 'bool'>, <class 'int'>, <class 'object'>)
Bituminous answered 5/4, 2012 at 19:47 Comment(1)
Also every (new style) class has a mro method, so you can call bool.mro() and True.__class__.mro() respectively (it returns list instead of tuple).Battue
A
2

You can also visualize class hierarchy as a picture.
I use Graphviz DOT and pyreverse to visualize and explore a large mess of classes (an example).

Assuming you want to draw all classes from tree.py in parso library:

# Generate classes_tree_full.png with full UML-style class boxes
$ pyreverse -mn    -o png -p tree_full  Lib\site-packages\parso\python\tree.py

# Generate classes_tree_short.png with only class names in boxes
$ pyreverse -mn -k -o png -p tree_short Lib\site-packages\parso\python\tree.py

Change -mn to -my if you want to see qualified class names, ex. parso.python.tree.Literal instead of just Literal.
Note: pyreverse also supports multiple files via globpatterns.

Alinaaline answered 18/2, 2022 at 21:42 Comment(0)
A
0

Hit command+o, then Press Ctrl+O to show parent hierarchy

checkout this blog http://pydev.blogspot.jp/2015/03/navigating-through-your-code-when-in.html

Autointoxication answered 10/8, 2016 at 2:11 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.