我开始使用Python编写各种项目的代码(包括Django web开发和Panda3D游戏开发)。

为了帮助我理解发生了什么,我想基本上“看看”Python对象内部,看看它们是如何运行的——比如它们的方法和属性。

假设我有一个Python对象,我需要什么来打印它的内容?这可能吗?


当前回答

import pprint

pprint.pprint(obj.__dict__)

or

pprint.pprint(vars(obj))

其他回答

Python有一组强大的自省特性。

看看下面的内置函数:

(型) dir () (id) getattr () hasattr () globals () locals () callable ()

Type()和dir()分别对于检查对象的类型及其属性集特别有用。

首先,阅读原文。

其次,使用dir()函数。

如果你有兴趣查看对象myobj对应的函数的源代码,你可以输入iPython或Jupyter Notebook:

myobj ? ?

Pprint和dir一起工作效果很好

你可以在shell中使用dir()列出对象的属性:

>>> dir(object())
['__class__', '__delattr__', '__doc__', '__format__', '__getattribute__', '__hash__', '__init__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__setattr__', '__sizeof__', '__str__', '__subclasshook__']

当然,还有inspect模块:http://docs.python.org/library/inspect.html#module-inspect