Skip to main content
 首页 » 编程设计

python之如何以类似于 Chrome 开发控制台中的 JS 对象的方式检查 Python 对象

2025年05月04日27zfyouxi

在 Chrome 开发控制台中,可以键入变量名称,输出是对象的可视化交互表示。 (在 JavaScript 中,对象就像字典,所以这很容易。)

我想在 Python 中拥有相同的功能。我很震惊我找不到任何类似的东西。例如,在 IPython GUI 控制台中,当我想检查变量 diff 时,在这种情况下我得到的是它的类型:

In [5]: diff 
Out[5]: <_pygit2.Diff at 0x1a69930> 

此命令检查变量,但对于复杂对象输出困惑(此处输出不完整):

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__', (...) 

我认为当语言没有类型系统时,实时自省(introspection)非常有用。也许此功能仅在特殊的 Python IDE 中可用?

展示它是如何在 Chrome 中完成的:

example of Chrome devtools object introspection

在图片上您可以看到变量f 的自省(introspection)。它是一个 Form 类型的对象,您可以单击它并查看其属性(例如 _meetingTimeFrom)及其值,您可以进一步单击属性来检查它们,您可以看到对象的方法(例如字段 __proto__,这可能是一种如何在 JavaScript 中查看对象方法的方式)。

请您参考如下方法:

如果你只是想以可读的方式列出属性,pprint.pprint 是你的 friend :

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 的 Original answer