栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 面试经验 > 面试问答

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

面试问答 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

在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'
,谜团结束了!



转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/626202.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号