<p>Perl中的<code>Dumper</code>给出了一个对象的表示,解释器可以<code>eval</code>将它转换为原始对象。Python中的对象的<code>repr</code>尝试这样做,有时这是可能的。一个<code>dict</code>的<code>repr</code>或一个<code>str</code>的<code>repr</code>可以做到这一点,像<code>datetime</code>和<code>timedelta</code>这样的类也可以做到这一点。因此<code>repr</code>相当于<code>Dumper</code>,但它并不漂亮,也没有显示对象的内部结构。为此,您可以使用<code>dir</code>并使用自己的打印机。你知道吗</p>
<p>下面是我在打印机上的一个示例,它不会产生可<code>eval</code>的Python代码,因此应该用来生成对象的字符串:</p>
<pre><code>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
</code></pre>
<p>在上面的示例中,我已经重写了对象的默认<code>__str__</code>实现。<code>__str__</code>是当您试图将对象表示为字符串或使用字符串格式化函数对其进行格式化时调用的函数。你知道吗</p>
<p>顺便说一句,<code>repr</code>是执行<code>print obj</code>时打印的内容,它调用该对象上的<code>__repr__</code>方法。有关如何控制对象格式的详细信息,请参见<a href="http://docs.python.org/reference/datamodel.html#object.__repr__" rel="nofollow noreferrer">the Python documentation of ^{<cd18>}</a>。你知道吗</p>
<pre><code># this would print the object's __repr__
print "%r" % c
# this would print the object's __str__
print "%s" % c
</code></pre>
<hr/>
<p>上面代码的输出是</p>
<pre><code>{'__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'}
</code></pre>