我认为你对文档的内容感到困惑.看看这两个文档部分:
Truth Value Testing and Boolean Operators.引用第一节的最后一段:
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.)
正如你所看到的,你对操作和内置函数是正确的,但是看到重要的异常部分,很明确的说,布尔运算符将返回其操作数之一.
现在,他们可以返回几乎不依赖于运算符的短路逻辑.对于或运算符,它将返回表达式中的第一个真实值,因为当它找到一个时,整个表达式是真的.在每个操作数都是伪造的情况下,或者将返回最后一个操作数,这意味着它会遍历每一个操作数都无法找到真实的操作数.
对于和运算符,如果表达式为true,它将返回最后一个操作数,如果表达式为false,则返回第一个falsey操作数.您可以阅读更多关于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'
我认为这应该是一个重点.为了帮助您进一步了解为什么这是有用的,请考虑以下示例:
您有一个随机生成名称的函数
import random
def generate_name():
return random.choice(['John', 'Carl', 'Tiffany'])
你有一个变量,你不知道它是否已经分配了一个名字,而不是做:
if var is None:
var = generate_name()
你可以做oneliner:
var = var or generate_name()
由于None是一个假值,否则将继续搜索并评估第二个操作数,这是调用该函数最终返回生成的名称.这是一个非常愚蠢的例子,我已经看到了这种风格的更好的用法(虽然不是在Python中).我现在不能出来一个更好的例子.你也可以看一看这个问题,有非常有用的答案主题:Does Python support short-circuiting?
最后但并非最不重要的是,这与静态类型,鸭型,动态,解释,编译,无论语言无关.这只是一个语言功能,可能会很方便,这是非常常见的,因为几乎所有的编程语言,我可以想到提供这个功能.
希望这可以帮助!