# 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'}
在我自己搜索了很多之后,我发现了这个翻车机,我现在通常导入。https://salmon-protocol.googlecode.com/svn-history/r24/trunk/salmon-playground/dumper.py
Perl中的
Dumper
给出了一个对象的表示,解释器可以eval
将它转换为原始对象。Python中的对象的repr
尝试这样做,有时这是可能的。一个dict
的repr
或一个str
的repr
可以做到这一点,像datetime
和timedelta
这样的类也可以做到这一点。因此repr
相当于Dumper
,但它并不漂亮,也没有显示对象的内部结构。为此,您可以使用dir
并使用自己的打印机。你知道吗下面是我在打印机上的一个示例,它不会产生可
eval
的Python代码,因此应该用来生成对象的字符串:在上面的示例中,我已经重写了对象的默认
__str__
实现。__str__
是当您试图将对象表示为字符串或使用字符串格式化函数对其进行格式化时调用的函数。你知道吗顺便说一句,} 。你知道吗
repr
是执行print obj
时打印的内容,它调用该对象上的__repr__
方法。有关如何控制对象格式的详细信息,请参见the Python documentation of ^{上面代码的输出是
相关问题 更多 >
编程相关推荐