python或运算符模块

gon*_*opp 7 python operators

operator模块上,我们有or_函数,它是按位或(|).

但是我似乎无法找到逻辑或(or).

文档似乎没有列出它.

我想知道为什么不包括在内?它不被视为运营商吗?

是否有内置函数提供其行为?

Mar*_*ers 14

or操作者的短路 ; 当左侧返回真值时,不评估右侧表达式.这也适用于and运营商; 当左侧表达式返回false值时,不评估右侧表达式.

你不能用一个函数做到这一点; 所有操作数进行评估功能,可以调用之前.因此,operator模块中没有相同的功能.

相比:

foo = None
result = foo and foo(bar)
Run Code Online (Sandbox Code Playgroud)

foo = None
result = operator.boolean_and(foo, foo(bar))  # hypothetical and implementation
Run Code Online (Sandbox Code Playgroud)

后一个表达式将失败,因为您不能将其None用作可调用对象.第一个版本有效,因为and运算符不会计算foo(bar)表达式.

  • @aruisdante:不,他不是.*在运算符模块上我们有`or_`函数*...*但是我似乎无法找到逻辑或*. (2认同)

nmc*_*ean 6

与内置or函数最接近的是any:

>>> any((1, 2))
True
Run Code Online (Sandbox Code Playgroud)

如果你想复制or返回非布尔操作数的功能,你可以使用next和filter:

>>> next(operand for operand in (1, 2) if operand)
1
Run Code Online (Sandbox Code Playgroud)

但就像Martijn所说的那样,or由于它的短路,它们都不是真正的替代品.真正的or函数必须接受函数才能避免评估所有结果:

logical_or(lambda: 1, lambda: 2)
Run Code Online (Sandbox Code Playgroud)

这有点笨拙,并且与operator模块的其余部分不一致,所以最好不要将它遗漏,而是使用其他显式方法.