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

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

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


当前回答

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

myobj ? ?

其他回答

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

看看下面的内置函数:

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

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

Pprint和dir一起工作效果很好

"""Visit http://diveintopython.net/"""

__author__ = "Mark Pilgrim (mark@diveintopython.org)"


def info(object, spacing=10, collapse=1):
    """Print methods and doc strings.

    Takes module, class, list, dictionary, or string."""
    methodList = [e for e in dir(object) if callable(getattr(object, e))]
    processFunc = collapse and (lambda s: " ".join(s.split())) or (lambda s: s)
    print "\n".join(["%s %s" %
                     (method.ljust(spacing),
                      processFunc(str(getattr(object, method).__doc__)))
                     for method in methodList])

if __name__ == "__main__":
    print help.__doc__

有一个python代码库构建就是为了这个目的:inspect在python 2.7中介绍过

已经有很多好的提示了,但还没有提到最短和最简单的(不一定是最好的):

object?