这里我要找的是PHP的print_r函数。

这样我就可以通过查看有问题的对象的状态来调试脚本。


当前回答

你实际上是把两种不同的东西混合在一起。

使用dir(), vars()或inspect模块来获取您感兴趣的内容(我使用__builtins__作为示例;你可以用任何物体代替)。

>>> l = dir(__builtins__)
>>> d = __builtins__.__dict__

随你喜欢,把那本词典打印出来吧:

>>> print l
['ArithmeticError', 'AssertionError', 'AttributeError',...

or

>>> from pprint import pprint
>>> pprint(l)
['ArithmeticError',
 'AssertionError',
 'AttributeError',
 'BaseException',
 'DeprecationWarning',
...

>>> pprint(d, indent=2)
{ 'ArithmeticError': <type 'exceptions.ArithmeticError'>,
  'AssertionError': <type 'exceptions.AssertionError'>,
  'AttributeError': <type 'exceptions.AttributeError'>,
...
  '_': [ 'ArithmeticError',
         'AssertionError',
         'AttributeError',
         'BaseException',
         'DeprecationWarning',
...

Pretty print也可以在交互式调试器中作为命令使用:

(Pdb) pp vars()
{'__builtins__': {'ArithmeticError': <type 'exceptions.ArithmeticError'>,
                  'AssertionError': <type 'exceptions.AssertionError'>,
                  'AttributeError': <type 'exceptions.AttributeError'>,
                  'BaseException': <type 'exceptions.BaseException'>,
                  'BufferError': <type 'exceptions.BufferError'>,
                  ...
                  'zip': <built-in function zip>},
 '__file__': 'pass.py',
 '__name__': '__main__'}

其他回答

无论你的变量在类中是如何定义的,在__init__内部还是外部,这都是有效的。

your_obj = YourObj()
attrs_with_value = {attr: getattr(your_obj, attr) for attr in dir(your_obj)}

如果你用它来调试,你只是想递归转储所有的东西,接受的答案是不令人满意的,因为它要求你的类已经有良好的__str__实现。如果不是这样的话,这样做会更好:

import json
print(json.dumps(YOUR_OBJECT, 
                 default=lambda obj: vars(obj),
                 indent=1))

从答案中,可以稍微修改一下,只得到一个对象的“Attributes”,如下所示:

def getAttributes(obj):
    from pprint import pprint
    from inspect import getmembers
    from types import FunctionType
    
    def attributes(obj):
        disallowed_names = {
          name for name, value in getmembers(type(obj)) 
            if isinstance(value, FunctionType)}
        return {
          name for name in dir(obj) 
            if name[0] != '_' and name not in disallowed_names and hasattr(obj, name)}
    pprint(attributes(obj))

在临时添加此函数时非常有用,并且可以在不修改现有源代码的情况下删除此函数

已经提到了Dir,但它只提供属性的名称。如果你也想要它们的值,试试__dict__。

class O:
   def __init__ (self):
      self.value = 3

o = O()

输出如下:

>>> o.__dict__

{'value': 3}

在大多数情况下,使用__dict__或dir()将获得你想要的信息。如果您碰巧需要更多的细节,标准库包括inspect模块,它允许您获得一些令人印象深刻的细节。一些真正宝贵的信息包括:

函数和方法参数的名称 类层次结构 实现一个函数/类对象的源代码 帧对象的局部变量

如果你只是在寻找“我的对象有哪些属性值?”,那么dir()和__dict__可能就足够了。如果您真的想深入研究任意对象的当前状态(请记住,在python中几乎所有东西都是对象),那么inspect值得考虑。