布尔“and”运算符的Python函数?

2024-04-20 10:19:33 发布

您现在位置:Python中文网/ 问答频道 /正文

我很惊讶在运算符模块中没有找到布尔(不是按位)and运算符:

http://docs.python.org/2/library/operator.html

为什么会这样?有解决办法吗?你知道吗


Tags: 模块andorghttpdocshtmllibrary运算符
2条回答

你可以自己写:

logical_and = lambda a, b: a and b

Python andor操作符对它们的表达式进行惰性计算,允许您使用如下表达式:

function_object and function_object(some, arguments)
some_value or produce_new_value(expensive, call)

安全地。你知道吗

这将取消它们进行operator处理的资格,因为您必须在将表达式传递给函数之前对其求值。你知道吗

在上面的例子中,这意味着and表达式不能用operator函数来表示;如果function_object为false-y,则可能也不可调用,如果some_value为true,则不希望调用代价高昂的函数调用。你知道吗

如果不需要延迟求值,那么创建自己的函数非常容易:

def and_(op1, op2):
    return op1 and op2

def or_(op1, op2):
    return op1 or op2

相关问题 更多 >