4

我的理解是&按位与运算符。所以我希望它在应用于逻辑时没有任何意义。但是,我看到:

>>> False & False
False
>>> False & True
False
>>> True & True
True

等等。对于其他位运算符也是如此。

那么,为什么这些运算符甚至接受逻辑操作数呢?我在哪里可以找到解释这一点的文档?我搜索了它,但找不到解释。

4

3 回答 3

8

那么,为什么这些运算符甚至接受逻辑操作数呢?

bool子类int和覆盖__and__()等以返回操作boolbool

有关详细信息,请参阅PEP 285

具体来说:

      6) bool 是否应该从 int 继承?

       => 是的

       在理想的世界中,bool 可能更好地实现为
       知道如何执行混合模式的单独整数类型
       算术。但是,从 int 继承 bool 可以简化
       极大地实现(部分原因是所有调用的 C 代码
       PyInt_Check() 将继续工作——这将返回 true
       int 的子类)。另外,我相信这是正确的
       可替代性:需要 int 的代码可以输入 bool
       它的行为与 0 或 1 相同。需要
       给定 int 时,bool 可能不起作用;例如,3 和 4
       为 0,但 3 和 4 都为真
       价值观。

    class bool(int):

        def __and__(self, other):
            if isinstance(other, bool):
                return bool(int(self) & int(other))
            else:
                return int.__and__(self, other)

        __rand__ = __and__

        def __or__(self, other):
            if isinstance(other, bool):
                return bool(int(self) | int(other))
            else:
                return int.__or__(self, other)

        __ror__ = __or__

        def __xor__(self, other):
            if isinstance(other, bool):
                return bool(int(self) ^ int(other))
            else:
                return int.__xor__(self, other)

        __rxor__ = __xor__

注意如何bool & bool返回一个boolbool & non-bool继承的int行为(即返回一个int)。

以下是一些演示这些属性的示例:

In [12]: isinstance(True, int)
Out[12]: True

In [13]: True & True
Out[13]: True

In [14]: True & 1
Out[14]: 1

上述行为不适用于算术运算符。那些只是使用int的行为:

In [15]: True + 0
Out[15]: 1

In [16]: True + False
Out[16]: 1
于 2012-12-16T17:37:37.817 回答
0

“逻辑”,也就是布尔值,只代表一个打开或关闭的位,所以当然按位运算对它们起作用。是什么让您期望按位运算不适用于单个位?

您正在反转逻辑操作的继承。按位运算的基本情况是针对单个位变量,例如布尔值。对较大值的按位运算只是单位运算的扩展应用。

于 2012-12-16T17:37:22.803 回答
0

在 Python 3.x 中,True 和 False 是关键字,总是等于 1 和 0。

在 Python 2 中的正常情况下,在 Python 3 中总是:

False 对象的类型为 bool,它是 int 的子类:

 object
  |
 int
  |
 bool
于 2012-12-16T17:39:22.367 回答