本帖最后由 飞畅 于 2020-8-19 01:54 编辑
[Python] 纯文本查看 复制代码
>>> a="C:\now"
>>> a.__repr__()
"'C:\\now'"
>>> a.__str__()
'C:\now'
>>> print(a.__repr__())
'C:\now'
>>> print(a.__str__())
C:
ow
个人理解:直接在控制台输入变量展示的时候,是通过字符串的内置函数__repr__()输出字符串的
print()输出展示的时候,是通过内置函数__str__()输出字符串的
前者主要用于调试,后者主要用于输出交互
更准确的还得看源码
https://www.python.org/downloads/source/
---------------------分割线------------------
源码分析:[https://www.python.org/ftp/python/3.6.4/Python-3.6.4.tgz]
在[Python/bltinmodule.c]里,看到了print的实现
[C] 纯文本查看 复制代码 static PyObject *
builtin_print(PyObject *self, PyObject *args, PyObject *kwds)
{
...
for (i = 0; i < PyTuple_Size(args); i++) {
if (i > 0) {
if (sep == NULL)
err = PyFile_WriteString(" ", file);
else
err = PyFile_WriteObject(sep, file,
Py_PRINT_RAW);
if (err)
return NULL;
}
err = PyFile_WriteObject(PyTuple_GetItem(args, i), file,
Py_PRINT_RAW);
if (err)
return NULL;
}
if (end == NULL)
err = PyFile_WriteString("\n", file);
else
err = PyFile_WriteObject(end, file, Py_PRINT_RAW);
if (err)
return NULL;
...
Py_RETURN_NONE;
}
也就是对print传来的参数元组,一个个的调用PyFile_WriteObject往文件里写,默认的是stdout
PyFile_WriteObject的实现
[Objects/fileobject.c]
[C] 纯文本查看 复制代码 int
PyFile_WriteObject(PyObject *v, PyObject *f, int flags)
{
...
if (flags & Py_PRINT_RAW) {
value = PyObject_Str(v);
}
else
value = PyObject_Repr(v);
if (value == NULL) {
Py_DECREF(writer);
return -1;
}
result = _PyObject_CallArg1(writer, value);
...
return 0;
}
可以看到如果是从builtin_print函数过来的话,flag参数就是Py_PRINT_RAW,两者位与为真,于是调用PyObject_Repr(v)获得要输出的字符串
否则,调用的就是PyObject_Str(v)
PyObject_Repr和PyObjet_Str的实现
[Objects/object.c]
[C] 纯文本查看 复制代码 PyObject *
PyObject_Repr(PyObject *v)
{
...
res = (*v->ob_type->tp_repr)(v);
...
return res;
}
PyObject *
PyObject_Str(PyObject *v)
{
...
res = (*Py_TYPE(v)->tp_str)(v);
...
return res;
}
PyObject_Repr和PyObject_Str内部会调__repr__和__str__ |