2009-06-17 90 views
168

我开始在各种使用Python的项目中进行编码(包括Django web开发和Panda3D游戏开发)。如何查看Python对象?

为了帮助我理解发生了什么,我想基本上'看'Python对象内部,看看它们是如何打勾的 - 就像他们的方法和属性一样。

所以说我有一个Python对象,我需要打印出它的内容?这甚至有可能吗?

回答

46

首先阅读源代码。

二,使用dir()函数。

+60

我想颠倒这个顺序。 – bayer 2009-06-17 10:19:21

+4

源代码比dir()更具信息性,并且有更好的开发习惯。 – 2009-06-17 11:05:53

+11

我不同意。 dir()的速度非常快,在99%的情况下,让你找出你需要的与帮助()的结合。 – bayer 2009-06-17 17:22:13

6

你可以列出一个对象在外壳DIR()属性:

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

当然,也有在检查模块:http://docs.python.org/library/inspect.html#module-inspect

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

__author__ = "Mark Pilgrim ([email protected])" 


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__ 
0

另外,如果你想看看里面名单和字典,你可以使用pprint()

2

pprint和dir共同努力伟大

4

如果你想看看参数和方法,正如其他人指出出来你可能使用pprintdir()

如果你想看到的内容的实际值,你可以做

object.__dict__

17

如果这是为了探索发生了什么,我建议看看IPython。这增加了各种快捷方式来获取对象文档,属性甚至源代码。例如添加一个“?”到一个函数将为对象提供帮助(实际上是“help(obj)”的快捷方式,如果可用,使用两个?(“func??”)将显示源代码。

还有很多额外的便利条件,比如制表符完成,漂亮的结果打印,结果历史记录等,这使得这种探索性编程非常方便。

更多程序中使用内省的,像dir()vars()getattr等基本建宏将是有益的,但它是值得你花时间检查出inspect模块。要获取一个函数的源代码,使用“inspect.getsource”,例如,将其应用到自己:

>>> 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, '') 

inspect.getargspec也经常有用的,如果你处理的包裹或操纵功能,因为它会给名称和默认函数参数的值。

6

其他人已经提到的目录()内置这听起来像你要找的东西,但这里的另一个很好的提示。许多图书馆 - 包括大部分标准图书馆 - 都以源代码形式分发。这意味着你可以很容易地直接读取源代码。诀窍在于找到它;例如:

>>> import string 
>>> string.__file__ 
'/usr/lib/python2.5/string.pyc' 

的* .pyc文件文件编译,所以删除尾随“C”和你最喜欢的编辑器或文件浏览器打开未编译的* .py文件:

/usr/lib/python2.5/string.py 

我已经发现这对于发现诸如从给定的API引发哪些异常等事情非常有用。这种细节在Python世界中很少有文档记载。

40

我很惊讶没有人提到的帮助呢!

In [1]: def foo(): 
    ...:  "foo!" 
    ...: 

In [2]: help(foo) 
Help on function foo in module __main__: 

foo() 
    foo! 

帮助,您可以阅读的文档字符串,并获得什么属性一类可能有,这是非常有益的一个想法。

1

如果你想看一个活体对象,那么python的inspect模块是一个很好的答案。通常,它用于获取源文件中定义的函数的源代码。如果您想获得在解释器中定义的实时函数和lambda表达式的源,可以使用dill中的dill.source.getsource。它也可以从curries中定义的绑定或未绑定类方法和函数获取代码...但是,如果没有包含对象的代码,您可能无法编译该代码。

>>> from dill.source import getsource 
>>> 
>>> def add(x,y): 
... return x+y 
... 
>>> squared = lambda x:x**2 
>>> 
>>> print getsource(add) 
def add(x,y): 
    return x+y 

>>> print getsource(squared) 
squared = lambda x:x**2 

>>> 
>>> class Foo(object): 
... def bar(self, x): 
...  return x*x+x 
... 
>>> f = Foo() 
>>> 
>>> print getsource(f.bar) 
def bar(self, x): 
    return x*x+x 

>>> 
2

有一个Python代码库的建立只是为了这个目的:inspect在Python 2.7

10

如果你有兴趣在这样的GUI介绍,看看objbrowser。它使用Python标准库中的inspect模块进行底层的对象自省。

objbrowserscreenshot

6

尝试ppretty

from ppretty import ppretty 


class A(object): 
    s = 5 

    def __init__(self): 
     self._p = 8 

    @property 
    def foo(self): 
     return range(10) 


print ppretty(A(), indent=' ', depth=2, width=30, seq_length=6, 
       show_protected=True, show_private=False, show_static=True, 
       show_properties=True, show_address=True) 

输出:

__main__.A at 0x1debd68L (
    _p = 8, 
    foo = [0, 1, 2, ..., 7, 8, 9], 
    s = 5 
) 
3

用于检查代码的两个伟大的工具:

  1. IPython。一个python终端,允许你使用tab完成检查。

  2. EclipsePyDev plugin。它有一个非常出色的调试器,可以让你在给定的位置中断,并通过浏览所有变量为树来检查对象。您甚至可以使用嵌入式终端在该位置尝试代码或输入对象并按'。'。让它为您提供代码提示。

enter image description here

0

VARS(obj)返回的对象的属性。

相关问题