python输出结果为false的是_用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)) {

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

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值