优秀的问题!我相信我有答案。这需要通过C中的Python源代码挖掘,所以忍受我。
首先,格式(obj,format_spec)只是obj .__格式__(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”,这个奥秘已经结束了!