& 和 <and> 在 python 中是否等价?

Are & and <and> equivalent in python?

使用单词 and 与 Python 中的 & 符号在逻辑或性能上有什么不同吗?

and 是布尔运算符。它将两个参数都视为布尔值,如果为假则返回第一个,否则返回第二个。请注意,如果第一个参数为假,则根本不会计算第二个参数,这对于避免副作用很重要。

示例:

  • False and True --> False
  • True and True --> True
  • 1 and 2 --> 2
  • False and None.explode() --> False(无一例外)

& 有两种行为。

  • 如果两者都是 int,则它计算两个数字的按位与,返回 int。如果一个是 int,一个是 bool,则 bool 值被强制转换为 int(如 0 或 1)并且应用相同的逻辑。
  • 否则,如果两者都是 bool,则计算两个参数并返回 bool
  • 否则会引发一个TypeError(如float & float等)。

示例:

  • 1 & 2 --> 0
  • 1 & True --> 1 & 1 --> 1
  • True & 2 --> 1 & 2 --> 0
  • True & True --> True
  • False & None.explode() --> AttributeError: 'NoneType' object has no attribute 'explode'