有没有Python模块能够提供比pprint更深入的数据结构分析?

2024-04-28 16:23:51 发布

您现在位置:Python中文网/ 问答频道 /正文

python中是否有任何东西可以让我以这样的方式转储一个随机对象,以便查看其底层数据表示?你知道吗

我来自Perl,Data::Dumper做了一项合理的工作,让我了解数据结构的布局。在python中有没有做同样事情的东西?你知道吗

谢谢!你知道吗


Tags: 对象数据结构data方式布局事情perl数据表示
2条回答

在我自己搜索了很多之后,我发现了这个翻车机,我现在通常导入。https://salmon-protocol.googlecode.com/svn-history/r24/trunk/salmon-playground/dumper.py

Perl中的Dumper给出了一个对象的表示,解释器可以eval将它转换为原始对象。Python中的对象的repr尝试这样做,有时这是可能的。一个dictrepr或一个strrepr可以做到这一点,像datetimetimedelta这样的类也可以做到这一点。因此repr相当于Dumper,但它并不漂亮,也没有显示对象的内部结构。为此,您可以使用dir并使用自己的打印机。你知道吗

下面是我在打印机上的一个示例,它不会产生可eval的Python代码,因此应该用来生成对象的字符串:

def dump(obj):
  out = {}

  for attr in dir(obj):
    out[attr] = getattr(obj, attr)

  from pprint import pformat
  return pformat(out)

class myclass(object):
  foo = 'foo'

  def __init__(self):
    self.bar = 'bar'

  def __str__(self):
    return dump(self)

c = myclass()
print c

在上面的示例中,我已经重写了对象的默认__str__实现。__str__是当您试图将对象表示为字符串或使用字符串格式化函数对其进行格式化时调用的函数。你知道吗

顺便说一句,repr是执行print obj时打印的内容,它调用该对象上的__repr__方法。有关如何控制对象格式的详细信息,请参见the Python documentation of ^{}。你知道吗

# this would print the object's __repr__
print "%r" % c

# this would print the object's __str__
print "%s" % c

上面代码的输出是

{'__class__': <class '__main__.myclass'>,
 '__delattr__': <method-wrapper '__delattr__' of myclass object at 0xb76deb0c>,
 '__dict__': {'bar': 'bar'},
 '__doc__': None,
 '__format__': <built-in method __format__ of myclass object at 0xb76deb0c>,
 '__getattribute__': <method-wrapper '__getattribute__' of myclass object at 0xb76deb0c>,
 '__hash__': <method-wrapper '__hash__' of myclass object at 0xb76deb0c>,
 '__init__': <bound method myclass.__init__ of <__main__.myclass object at 0xb76deb0c>>,
 '__module__': '__main__',
 '__new__': <built-in method __new__ of type object at 0x82358a0>,
 '__reduce__': <built-in method __reduce__ of myclass object at 0xb76deb0c>,
 '__reduce_ex__': <built-in method __reduce_ex__ of myclass object at 0xb76deb0c>,
 '__repr__': <method-wrapper '__repr__' of myclass object at 0xb76deb0c>,
 '__setattr__': <method-wrapper '__setattr__' of myclass object at 0xb76deb0c>,
 '__sizeof__': <built-in method __sizeof__ of myclass object at 0xb76deb0c>,
 '__str__': <bound method myclass.__str__ of <__main__.myclass object at 0xb76deb0c>>,
 '__subclasshook__': <built-in method __subclasshook__ of type object at 0x896ad34>,
 '__weakref__': None,
 'bar': 'bar',
 'foo': 'foo'}

相关问题 更多 >