How to inspect Python objects in similar way like JS objects in Chrome dev console?
在chrome开发控制台中,可以输入变量的名称,输出是对象的可视化和交互式表示。(在javascript中,对象类似于字典,所以这很容易。)
我希望在Python中具有相同的功能。我很震惊,我找不到类似的东西。例如,在IPython GUI控制台中,当我想检查变量
1 2 | In [5]: diff Out[5]: <_pygit2.Diff at 0x1a69930> |
此命令检查变量,但复杂对象的输出是混沌的(此处输出不完整):
1 2 | In [10]: inspect.getmembers(diff) Out[10]: [('__class__', <type '_pygit2.Diff'>), ('__delattr__', <method-wrapper '__delattr__' of _pygit2.Diff object at 0x1a69930>), ('__doc__', 'Diff objects.'), ('__format__', <built-in method __format__ of _pygit2.Diff object at 0x1a69930>), ('__getattribute__', (...) |
我认为当语言没有类型系统时,一个实时的自省是非常有用的。也许这个功能只在特殊的python-ide中可用?
要显示如何在Chrome中完成:
在图片上,你可以看到一个变量
如果您只想以可读的方式列出属性,那么
1 2 3 4 5 6 7 8 9 10 11 12 | from pprint import pprint from inspect import getmembers class X: def __init__(self, x, y): self.x = x self.y = y x = X([42] * 5, [True] * 15) pprint(getmembers(x)) pprint(vars(x)) |
If you're interested in a GUI for this, take a look at
objbrowser. It uses the inspect module from the Python standard
library for the object introspection underneath.
Titusjan的原始答案