Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/string/5.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python打印使用哪个函数?_Python_String_Printing_Repr - Fatal编程技术网

Python打印使用哪个函数?

Python打印使用哪个函数?,python,string,printing,repr,Python,String,Printing,Repr,我有一个打印到终端的对象,它看起来像这样: >>> print b <p>„De neergang kan een duikvlucht worden.”</p> >>打印b “德尼尔冈可以用两个字。” 所以我想知道这个结果是从哪个函数得到的。因此,我尝试了以下方法: >>> b.__repr__() '<lxml.etree._XSLTResultTree object at 0x112c6a980>' >>

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

>>> print b
<p>„De neergang kan een duikvlucht worden.”</p>
>>打印b
“德尼尔冈可以用两个字。”

所以我想知道这个结果是从哪个函数得到的。因此,我尝试了以下方法:

>>> 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>'
>>>b._urepr____;
''
>>>b.uuu str_uuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuu
“\xe2\x80\x9eDe neergang kan een duikvlucht worden.\xe2\x80\x9d

” >>>b.uuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuu “u”\u201eDe neergang可以用两个字。\u201d

'
如您所见,这两个函数都不显示
print
语句所显示的内容。我一直认为,
print
实际上显示了
\uuu repr\uuuu()
\uu str\uuuu()
\uuu unicode\uuu()
的结果,但情况显然不是这样


那么,
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
(作为一个函数,我没有检查操作码,尽管我认为它是相同的)使用Py\u print\u RAW标志调用PyFile\u WriteObject

int PyFile_WriteObject(PyObject*obj,PyObject*p,int标志)

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

object.\uuuu str\uuuuuu(self)

str(object)
和内置函数
format()
print()
调用,以计算对象的“非正式”或可良好打印的字符串表示形式。返回值必须>为字符串对象

这是来自python的。很明显,
print
函数将调用defined
\uuuuu str()\uuuuu
,如果您在类中同时定义了
\uuuuuu str()\uuuuuu
。但是,如果您只是实现了
\uuuurepr()\uuuuu
,那么
打印(对象)
应该使用
\uuuuurepr()\uuuu


希望这会有所帮助。

它是
\uuuuu str\uuuuuuuuuu
,但是当你只做
b.\uuuuuuu struuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuu()
时,实际上是在做
打印b.\uuuuuuuuuuuuuuuu struuuuuuuuuuuuuuuuuuuuuuuuuuuu