gpt4 book ai didi

python - 二元运算符应用于逻辑时意味着什么?

转载 作者:太空狗 更新时间:2023-10-30 02:12:43 25 4
gpt4 key购买 nike

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

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

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

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

最佳答案

So, why do these operators even accept logical operands?

bool 子类 int,并覆盖 __and__() 等以返回 bool for bool 操作数。

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

具体来说:

      6) Should bool inherit from int?       => Yes       In an ideal world, bool might be better implemented as a       separate integer type that knows how to perform mixed-mode       arithmetic.  However, inheriting bool from int eases the       implementation enormously (in part since all C code that calls       PyInt_Check() will continue to work -- this returns true for       subclasses of int).  Also, I believe this is right in terms of       substitutability: code that requires an int can be fed a bool       and it will behave the same as 0 or 1.  Code that requires a       bool may not work when it is given an int; for example, 3 & 4       is 0, but both 3 and 4 are true when considered as truth       values.

and

    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

关于python - 二元运算符应用于逻辑时意味着什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13903773/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com