了解非布尔运算符在布尔值上的使用

Understanding the use of non Boolean operators on Booleans

我一直在尝试对布尔值使用 +-*/ 运算符,但我不明白我的奇怪输出结果得到:

第一个例子使用 +:

>>> a = True
>>> b = False
>>> a + b
1
>>> a + a
2 
>>> b + b
0

很明显我没有得到布尔值输出,果然如此:

>>> type(a + a)
<class 'int'>
>>>

第二个例子使用-

>>> a - b
1
>>> a - a
0
>>>b - b
0

所有整数再次出现。

第三个例子使用*

>>> a * a
1
>>> a * b 
0
>>> b * b
0
>>>

最后使用 /(返回错误):

>>> a / a
1.0
>>> a / b
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
ZeroDivisionError: division by zero
>>> b / b
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
ZeroDivisionError: division by zero
>>>

有趣的是:

>>> type(a / a)
<class 'float'>
>>>

Returns 一个浮动。

这是怎么回事。为什么我在使用非布尔运算符而不是我期望的布尔运算符时得到这些整数和浮点数输出?

基本上True等于整数1,False等于整数0。 这是因为 Boolean 是 int 的子类。

您可以通过将布尔值转换为整数来获得这些值:

int(True)
int(False)

booleanint 的子类。 FalseTrue 分别有。 0 和 1 值。

加法时,使用int的加法方法,boolean不会重新定义__add____sub__(或mul或div.. .) 所以结果是 int 类型,即使 False + TrueFalse + False 可以适合布尔类型(一种加法方法 return 一个整数或一个布尔值取决于在射程上会有点奇怪)。

>>> bool.__add__ is int.__add__
True
>>> bool.__sub__ is int.__sub__
True

type(a / a)float 因为 python 3 浮点数 div 甚至在整数之间。如果您需要 int,请执行 type(a // a)