在python中打印类堆栈

时间:2015-01-23 22:00:25

标签: python

我有以下三个类:

class foo(object):
    pass
class bar(foo):
    pass
class baz(bar):
    pass

我想要一个像这样的方法:

>>> class_stack(baz)
baz > bar > foo

1 个答案:

答案 0 :(得分:5)

也许您正在寻找MRO (method resolution order)

In [32]: baz.mro()
Out[32]: [__main__.baz, __main__.bar, __main__.foo, object]

In [33]: [cls.__name__ for cls in baz.mro()]
Out[33]: ['baz', 'bar', 'foo', 'object']

In [34]: ' > '.join([cls.__name__ for cls in baz.mro()])
Out[34]: 'baz > bar > foo > object'