在Python中使用format()方法打印布尔值TrueFalse

在Python中使用format()方法打印布尔值TrueFalse,第1张

在Python中使用format()方法打印布尔值True / False

很好的问题!我相信我有答案。这需要深入研究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'
,谜团结束了!



欢迎分享,转载请注明来源:内存溢出

原文地址: https://outofmemory.cn/zaji/5632087.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
上一篇 2022-12-15
下一篇 2022-12-15

发表评论

登录后才能评论

评论列表(0条)

保存