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

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

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


当前回答

如果这是为了探究发生了什么,我建议查看IPython。这增加了获取对象文档、属性甚至源代码的各种快捷方式。例如,在函数后附加一个"?"将为对象提供帮助(有效地为"help(obj)"提供快捷方式),而使用两个"?" ("func??")将在可用时显示源代码。

还有很多额外的便利,如制表符补全、结果打印、结果历史记录等,这对于这种探索性编程非常方便。

对于内省的更多编程使用,基本的内置程序,如dir(), vars(), getattr等将是有用的,但值得您花时间检查inspect模块。要获取一个函数的源,使用inspect。例如,将其应用到自身:

>>> print inspect.getsource(inspect.getsource)
def getsource(object):
    """Return the text of the source code for an object.

    The argument may be a module, class, method, function, traceback, frame,
    or code object.  The source code is returned as a single string.  An
    IOError is raised if the source code cannot be retrieved."""
    lines, lnum = getsourcelines(object)
    return string.join(lines, '')

检查。如果处理包装或操作函数,Getargspec通常也很有用,因为它将给出函数参数的名称和默认值。

其他回答

首先,阅读原文。

其次,使用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

如果这是为了探究发生了什么,我建议查看IPython。这增加了获取对象文档、属性甚至源代码的各种快捷方式。例如,在函数后附加一个"?"将为对象提供帮助(有效地为"help(obj)"提供快捷方式),而使用两个"?" ("func??")将在可用时显示源代码。

还有很多额外的便利,如制表符补全、结果打印、结果历史记录等,这对于这种探索性编程非常方便。

对于内省的更多编程使用,基本的内置程序,如dir(), vars(), getattr等将是有用的,但值得您花时间检查inspect模块。要获取一个函数的源,使用inspect。例如,将其应用到自身:

>>> print inspect.getsource(inspect.getsource)
def getsource(object):
    """Return the text of the source code for an object.

    The argument may be a module, class, method, function, traceback, frame,
    or code object.  The source code is returned as a single string.  An
    IOError is raised if the source code cannot be retrieved."""
    lines, lnum = getsourcelines(object)
    return string.join(lines, '')

检查。如果处理包装或操作函数,Getargspec通常也很有用,因为它将给出函数参数的名称和默认值。

Pprint和dir一起工作效果很好

此外,如果您想查看列表和字典内部,可以使用pprint()