很好的问题!我相信我有答案。这需要深入研究C语言中的Python源代码,所以请多多包涵。
首先,
format(obj,format_spec)只是的语法糖
obj.__format__(format_spec)。对于发生这种情况的特定位置,您必须在函数中查看abstract.c:
PyObject *PyObject_Format(PyObject* obj, PyObject *format_spec){ PyObject *empty = NULL; PyObject *result = NULL; ... if (PyInstance_Check(obj)) { HERE -> PyObject *bound_method = PyObject_GetAttrString(obj, "__format__"); if (bound_method != NULL) { result = PyObject_CallFunctionObjArgs(bound_method, format_spec, NULL); ...}
为了找到确切的调用,我们必须查看intobject.c:
static PyObject *int__format__(PyObject *self, PyObject *args){ PyObject *format_spec; ... return _PyInt_FormatAdvanced(self, ^PyBytes_AS_STRING(format_spec), |PyBytes_GET_SIZE(format_spec)); LET'S FIND THIS ...}
_PyInt_FormatAdvanced实际上定义为在宏formatter_string.c作为函数中发现formatter.h:
static PyObject*format_int_or_long(PyObject* obj, STRINGLIB_CHAR *format_spec,Py_ssize_t format_spec_len,IntOrLongToString tostring){ PyObject *result = NULL; PyObject *tmp = NULL; InternalFormatSpec format; if (format_spec_len == 0) { result = STRINGLIB_TOSTR(obj); <- EXPLICIT CAST alert! goto done; } ... // Otherwise, format the object as if it were an integer}
答案就在这里。简单检查是否
format_spec_len为
0,如果是,则将其转换
obj为字符串。如您所知,
str(True)是
'True',谜团结束了!
欢迎分享,转载请注明来源:内存溢出
评论列表(0条)