Python打印使用哪个功能?

问题描述 投票:0回答:2

我有一个打印到终端的对象,它看起来像这样:

>>> print b
<p>„De neergang kan een duikvlucht worden.”</p>

所以我想知道结果是哪个函数。所以我尝试了以下方法:

>>> b.__repr__()
'<lxml.etree._XSLTResultTree object at 0x112c6a980>'
>>> b.__str__()
'\xe2\x80\x9eDe neergang kan een duikvlucht worden.\xe2\x80\x9d</p>'
>>> b.__unicode__()
'u'<p>\u201eDe neergang kan een duikvlucht worden.\u201d</p>'

如您所见,这些函数都不会显示print语句显示的内容。我一直认为print实际上显示了__repr__()__str__()__unicode__()的结果,但事实显然并非如此。

那么print实际上叫什么?

python string printing repr
2个回答
2
投票

检查这类事情很容易:

>>> class C(object):
    def __repr__(self):
        print("repr called")
        return "repr"
    def __str__(self):
        print("str called")
        return "str"
    def __unicode__(self):
        print("unicode called")
        return "unicode"


>>> print C()
str called
str
>>> 

事实上,内部发生的是print(作为一个函数,我没有检查操作码,虽然我认为它是相同的)使用Py_PRINT_RAW标志调用PyFile_WriteObject。

int PyFile_WriteObject(PyObject * obj,PyObject * p,int flags)

将对象obj写入文件对象p。标志唯一支持的标志是Py_PRINT_RAW;如果给定,则写入对象的str()而不是repr()。成功时返回0或失败时返回-1;将设置适当的例外。


0
投票

object.__str__(self)

str(object)和内置函数format()print()调用来计算对象的“非正式”或可打印的字符串表示。返回值必须>是一个字符串对象。

这是来自python documentation。很明显,如果在类中定义print__str()____str()__函数将调用定义的__repr()__。但是如果你只是实施__repr()__,那么print(object)将使用__repr()__

希望这会有所帮助。

© www.soinside.com 2019 - 2024. All rights reserved.