Python print 使用了哪个函数?
Which function does Python print use?
我有一个打印到终端的对象,它看起来像这样:
>>> 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
实际上叫什么?
检查这类事情很容易:
>>> 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
(作为一个函数,我没有检查操作码,尽管我认为它是相同的)调用 PyFile_WriteObject 和 Py_PRINT_RAW旗帜。
int PyFile_WriteObject(PyObject *obj, PyObject *p, int flags)
Write
object obj to file object p. The only supported flag for flags is
Py_PRINT_RAW; if given, the str() of the object is written instead of
the repr(). Return 0 on success or -1 on failure; the appropriate
exception will be set.
object.__str__(self)
Called by str(object)
and the built-in functions format()
and print()
to compute the >'informal' or nicely printable string representation of an object. The return value must >be a string object.
本文来自 python documentation。很明显,如果在 class 中同时定义 __str()__
和 __repr()__
,print
函数将调用定义的 __str()__
。但是如果你只是实现 __repr()__
,那么 print(object)
应该使用 __repr()__
.
希望这会有所帮助。
我有一个打印到终端的对象,它看起来像这样:
>>> 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
实际上叫什么?
检查这类事情很容易:
>>> 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
(作为一个函数,我没有检查操作码,尽管我认为它是相同的)调用 PyFile_WriteObject 和 Py_PRINT_RAW旗帜。
int PyFile_WriteObject(PyObject *obj, PyObject *p, int flags)
Write object obj to file object p. The only supported flag for flags is Py_PRINT_RAW; if given, the str() of the object is written instead of the repr(). Return 0 on success or -1 on failure; the appropriate exception will be set.
object.__str__(self)
Called by
str(object)
and the built-in functionsformat()
andprint()
to compute the >'informal' or nicely printable string representation of an object. The return value must >be a string object.
本文来自 python documentation。很明显,如果在 class 中同时定义 __str()__
和 __repr()__
,print
函数将调用定义的 __str()__
。但是如果你只是实现 __repr()__
,那么 print(object)
应该使用 __repr()__
.
希望这会有所帮助。