开发者

Why does concatenating a boolean value return an integer?

开发者 https://www.devze.com 2022-12-22 03:27 出处:网络
In python, you can concatenate boolean values, and it would return an integer. Example: >>> True

In python, you can concatenate boolean values, and it would return an integer. Example:

>>> True
True
>>> True + True
2
>>> True + False
1
>>> True + True + True
3
>>> True + True + False
2
>>> False + False
0

Why? Why does this make sense?

I understand that True is often represented as 1, whereas False is represented as 0, but that still does not explai开发者_如何学Pythonn how adding two values together of the same type returns a completely different type.


Because In Python, bool is the subclass/subtype of int.

>>> issubclass(bool,int)
True

Update:

From 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 */


Replace "concatenate" with "add" and True/False with 1/0, as you've said, and it makes perfect sense.

To sum up True and False in a sentence: they're alternative ways to spell the integer values 1 and 0, with the single difference that str() and repr() return the strings 'True' and 'False' instead of '1' and '0'.

See also: http://www.python.org/dev/doc/maint23/whatsnew/section-bool.html


True is 1
False is 0
+ is ADD

Try this:

IDLE 2.6.4      
>>> True == 1
True
>>> False == 0
True
>>> 
0

精彩评论

暂无评论...
验证码 换一张
取 消