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

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


当前回答

一个有魔力的元编程示例转储对象:

$ cat dump.py
#!/usr/bin/python
import sys
if len(sys.argv) > 2:
    module, metaklass  = sys.argv[1:3]
    m = __import__(module, globals(), locals(), [metaklass])
    __metaclass__ = getattr(m, metaklass)

class Data:
    def __init__(self):
        self.num = 38
        self.lst = ['a','b','c']
        self.str = 'spam'
    dumps   = lambda self: repr(self)
    __str__ = lambda self: self.dumps()

data = Data()
print data

无参数:

$ python dump.py
<__main__.Data instance at 0x00A052D8>

与Gnosis Utils:

$ python dump.py gnosis.magic MetaXMLPickler
<?xml version="1.0"?>
<!DOCTYPE PyObject SYSTEM "PyObjects.dtd">
<PyObject module="__main__" class="Data" id="11038416">
<attr name="lst" type="list" id="11196136" >
  <item type="string" value="a" />
  <item type="string" value="b" />
  <item type="string" value="c" />
</attr>
<attr name="num" type="numeric" value="38" />
<attr name="str" type="string" value="spam" />
</PyObject>

虽然有点过时,但还能用。

其他回答

我没有测试过性能,但我相信这是在Python中以列表形式枚举任何对象的属性/属性/键的最快方法。

# If core==False, ignore __k__ entries
def obj_props(obj, core=False) -> list:
    assert not obj is None, f"obj must not be null (None)"
    _props = []
    _use_dir=False
    def _add(p):
        if not core and p.find('__') == 0: return
        _props.append(p)
    if hasattr(obj, '__dict__'): 
        for p in obj.__dict__.keys(): _add(p)
    elif hasattr(obj, '__slots__'):
        for p in obj.__slots__: _add(p)
    elif hasattr(obj, 'keys'):
        try:
            for p in obj.keys(): _add(p)
        except Exception as ex:
            _props = []
            _use_dir = True
    else:
        _use_dir = True
    if _use_dir:
        # fall back to slow and steady
        for p in dir(obj):
            if not core and p.find('__') == 0: continue
            v = getattr(obj, p)
            v_t = type(v).__name__
            if v_t in ('function', 'method', 'builtin_function_or_method', 'method-wrapper'): continue
            _props.append(p)

    return _props

上面应该适用于常规的python对象(使用__dict__),使用插槽的对象(__slots__),甚至适用于像对象一样的字典。

大多数其他示例使用dir(obj),它将枚举对象的所有方法和属性,如果您只需要它的属性,则会对性能造成影响。

def dump(obj):
  for attr in dir(obj):
    print("obj.%s = %r" % (attr, getattr(obj, attr)))

有许多第三方函数根据作者的喜好添加了异常处理、国家/特殊字符打印、递归嵌套对象等功能。但它们基本上都可以归结为这个。

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

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

从答案中,可以稍微修改一下,只得到一个对象的“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(), 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__'}