为什么连接布尔值会返回整数?
在Python中,你可以把布尔值(也就是真和假)连接在一起,这样做会返回一个整数。举个例子:
>>> True
True
>>> True + True
2
>>> True + False
1
>>> True + True + True
3
>>> True + True + False
2
>>> False + False
0
为什么会这样呢?这有什么道理吗?
我知道True
通常被表示为1
,而False
则表示为0
,但这仍然不能解释为什么把同类型的两个值加在一起会返回一个完全不同的类型。
3 个回答
2
True is 1
False is 0
+ is ADD
IDLE 2.6.4
>>> True == 1
True
>>> False == 0
True
>>>
试试这个:
8
把“连接”换成“加”,把 True
和 False
换成 1
和 0
,就像你说的,这样就很容易理解了。
简单来说,
True
和False
就是数字 1 和 0 的另一种写法,唯一的不同是用str()
和repr()
函数时,它们会返回字符串 'True' 和 'False',而不是 '1' 和 '0'。
更多信息请查看: http://www.python.org/dev/doc/maint23/whatsnew/section-bool.html
21
因为在Python中,bool
是 int
的子类,也就是说,布尔值是整数的一种特殊类型。
>>> issubclass(bool,int)
True
更新:
来自 boolobject.c
/* Boolean type, a subtype of int */
/* We need to define bool_print to override int_print */
bool_print
fputs(self->ob_ival == 0 ? "False" : "True", fp);
/* We define bool_repr to return "False" or "True" */
bool_repr
...
/* We define bool_new to always return either Py_True or Py_False */
...
// Arithmetic methods -- only so we can override &, |, ^
bool_as_number
bool_and, /* nb_and */
bool_xor, /* nb_xor */
bool_or, /* nb_or */
PyBool_Type
"bool",
sizeof(PyIntObject),
(printfunc)bool_print, /* tp_print */
(reprfunc)bool_repr, /* tp_repr */
&bool_as_number, /* tp_as_number */
(reprfunc)bool_repr, /* tp_str */
&PyInt_Type, /* tp_base */
bool_new, /* tp_new */