有没有一种简单的方法可以树形形式打印类的层次结构?

Hes*_*shy 4 python multiple-inheritance graph-visualization

有没有可以像git log --graphgit commits 那样以树形形式打印python类的继承关系的函数?

我想做的事的例子:

class A(object): pass
class B(A): pass
class C(B): pass
class D(A): pass
class E(C, D): pass

printtree(E)
Run Code Online (Sandbox Code Playgroud)

输出看起来像的示例(但可以使用变化形式)。奖励点是,如果mro也可以直接从图形中读取,就像我从上到下所做的那样,但是如果不是,那也很好。

class A(object): pass
class B(A): pass
class C(B): pass
class D(A): pass
class E(C, D): pass

printtree(E)
Run Code Online (Sandbox Code Playgroud)

Mar*_*ers 5

No, there is no built-in function to do this, you'd have to build your own. But know that laying out and drawing ASCII graphs is a complicated task, the Mercurial graphing code (a Python equivalent of git log --graph) is quite involved and complicated.

It'd be much more productive to leave graph layouts to a dedicated utility like Graphviz. Someone has already written the code to do this, see this article by Michele Simionato, Ph. D, where they turn:

class M(type): pass # metaclass
class F(object): pass
class E(object): pass
class D(object): pass
class G(object): __metaclass__=M
class C(F,D,G): pass
class B(E,D): pass
class A(B,C): pass
Run Code Online (Sandbox Code Playgroud)

into

在此处输入图片说明

complete with the full MRO outlined in a label. While the code was written over 15 years ago, it still works, as designed, on Python 3 (I tested with 3.8.0a1).