布尔运算符与按位运算符 [英] Boolean operators vs Bitwise operators

查看:96
本文介绍了布尔运算符与按位运算符的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

对于何时应该使用布尔运算符还是按位运算符,我感到困惑

I am confused as to when I should use Boolean vs bitwise operators

  • and &
  • or |

有人能启发我何时使用每种药物,何时使用一种药物会影响我的结果?

Could someone enlighten me as to when do i use each and when will using one over the other affect my results?

推荐答案

以下是一些准则:

  • 布尔运算符通常用于 boolean 值,而按位运算符通常用于 integer 值.
  • 布尔运算符是短路,而按位运算符是不是短路.
  • Boolean operators are usually used on boolean values but bitwise operators are usually used on integer values.
  • Boolean operators are short-circuiting but bitwise operators are not short-circuiting.

短路行为在这样的表达式中很有用:

The short-circuiting behaviour is useful in expressions like this:

if x is not None and x.foo == 42:
    # ...

这对于按位& 运算符将无法正常工作,因为总是会评估双方,从而给出 AttributeError:'NoneType'对象没有属性'foo'.当您使用布尔值运算符时,如果第一个为False,则不对第二个表达式求值.同样,如果第一个为True,则 or 不会计算第二个参数.

This would not work correctly with the bitwise & operator because both sides would always be evaluated, giving AttributeError: 'NoneType' object has no attribute 'foo'. When you use the boolean andoperator the second expression is not evaluated when the first is False. Similarly or does not evaluate the second argument if the first is True.

这篇关于布尔运算符与按位运算符的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆