python - 移位运算符和二进制按位运算符适用于 bool 参数

标签 python python-3.3

shifting operations 的 Python 文档和 binary bitwise operations说参数必须是整数,但下面的表达式计算没有错误,但是给出了 << 的奇怪结果和 >> .

我应该在其他地方寻找 & 的文档吗?等等。当使用 bool 参数时,或者对评估和结果有一些好的解释吗?

  • 真与假:假(类“bool”)
  • 正确 |假:真(类“ bool ”)
  • 正确 ^ 错误:正确(类“bool”)
  • ~ 正确:-2(类“int”)
  • ~ 错误:-1(类“int”)
  • 正确 << 正确:2(类“int”)
  • 错误 >> 错误:0(类“int”)

代码:

# Python ver. 3.3.2

def tryout(s):
    print(s + ':', eval(s), type(eval(s)))

tryout('True & False')
tryout('True | False')
tryout('True ^ False')
tryout('~ True')
tryout('~ False')
tryout('True << True')
tryout('False >> False')

最佳答案

bool int 的子类,因此它们整数。特别是True表现得像 1False表现得像 0 .

请注意 bool 重新实现& , |^ (来源:python 源中 Objects/boolobject.c 的源代码),对于所有其他操作,int 的方法使用[实际上:继承],因此结果是int s 和语义是整数的语义。

关于 <<>> , 表达式 True << True相当于1 << 11 * 2 == 2 , 而 False >> False0 >> 0 ,即 0 * 1 == 0 .

你应该想到python的TrueFalse作为10在对它们进行算术运算时。 &的重新实现, |^ affect the return type ,而不是语义。

关于python - 移位运算符和二进制按位运算符适用于 bool 参数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18379847/

相关文章:

python - 使文本看起来像是在 Python Shell 中输入的

从 MS Access 导入 Python : "Invalid connection string attribute"

python - 处理正则表达式组中的字符串后替换所有出现的正则表达式组

python - 迭代多索引数据帧(Python)并将字典分配给索引值对

python - 在 Django 中更改使用 ModelForm 创建的表单元素的宽度

python - 无法为 Selenium 使用 chrome 驱动程序

python - 升级后的Pylab

python - 如何根据与前一行的差异对行进行分组?

python - 来自 netcdf 的 Xarray 数据数组返回大于输入的 numpy 网格数组

python - 测试没有重复元素的列表