Operations and built-in functions that have a Boolean result always return 0 or False for false and 1 or True for true, unless otherwise stated. (Important exception: the Boolean operations or and and always return one of their operands.)
如您所见,关于操作和内置函数,您是正确的,但是请参见重要异常部分,很好地说明了布尔运算符将返回其一个操作数。在
现在,他们能返回什么几乎不取决于操作员的短路逻辑。对于or运算符,它将返回表达式中的第一个truthy值,因为当它找到一个值时,整个表达式都是真的。如果每个操作数都是假,or将返回最后一个操作数,这意味着它迭代每个操作数都找不到一个真操作数。在
对于and运算符,如果表达式为true,则返回最后一个操作数;如果表达式为false,则返回第一个false操作数。您可以阅读有关Short Circuit Evaluation at the Wikipedia Page的更多信息。在
你的问题中有很多例子,我们来分析一下:>>> False and 1 # return false (short circuited at first falsey value)
False
>>> True and 1 # return 1 (never short circuited and return the last truthy value)
1
>>> 1 and False # return false (short circuited at first falsey value, in this case the last operand)
False
>>> 1 and True # return True (never short circuited and return the last truthy value)
True
>>> True and 121 # return 121 (never short circuited and return the last truthy value)
121
>>> False or 1 # return 1 (since the first operand was falsey, or kept looking for a first truthy value which happened to be the last operator)
1
>>> False or 112 # return 112 for same reason as above
112
>>> False or "Khadijah" # return "Khadijah" for same reason as above
'Khadijah'
>>> True and 'Khadijah' # return "Khadijah" because same reason as second example
'Khadijah'
我认为这应该说明问题。为了帮助您进一步了解为什么这是有用的,请考虑以下示例:
你有一个随机生成名字的函数
^{pr2}$
你有一个变量,你不知道它是否已经分配了一个名称,而不是这样做:if var is None:
var = generate_name()
您可以使用oneliner:var = var or generate_name()
由于None是一个假值,or将继续搜索并计算第二个操作数,即调用最终返回生成名称的函数。这是一个非常愚蠢的例子,我见过这种风格更好的用法(尽管在Python中没有)。我现在没有比这更好的例子了。你也可以看看这个问题,关于这个主题有很多有用的答案:Does Python support short-circuiting?
最后但并非最不重要的一点是,这与静态类型、duck类型、动态、解释、编译等任何语言无关。它只是一个语言特性,一个可能很有用的特性,这是非常常见的,因为我能想到的几乎所有编程语言都提供了这个特性。在
希望这有帮助!在