好问题!我相信我有答案。这需要在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)) {
/* We're an instance of a classic class */
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;
/* check for the special case of zero length format spec, make
it equivalent to str(obj) */
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',谜团结束了!