在python中,您可以连接布尔值,它将返回一个整数.例:
>>> True
True
>>> True + True
2
>>> True + False
1
>>> True + True + True
3
>>> True + True + False
2
>>> False + False
0
Run Code Online (Sandbox Code Playgroud)
为什么?为什么这有意义?
我理解这True通常表示为1,而False表示为0,但仍然没有解释如何将相同类型的两个值相加返回一个完全不同的类型.
YOU*_*YOU 21
因为在Python中,bool是子类/子类型int.
>>> issubclass(bool,int)
True
Run Code Online (Sandbox Code Playgroud)
更新:
/* 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 */
Run Code Online (Sandbox Code Playgroud)
正如你所说的那样,将"concatenate"替换为"add"和True/ Falsewith 1/ 0,这非常有意义.
总结一句话中的真与假:它们是拼写整数值1和0的替代方法,唯一的区别是str()和repr()返回字符串'True'和'False'而不是'1 '和'0'.
另见:http://www.python.org/dev/doc/maint23/whatsnew/section-bool.html
| 归档时间: |
|
| 查看次数: |
593 次 |
| 最近记录: |