我认为您对文档所说的内容感到困惑。看一下这两个文档部分:真值测试和布尔运算符 http://docs.python.org/2/library/stdtypes.html?highlight=short%20circuit#truth-value-testing。引用第一部分的最后一段:
具有布尔结果的运算和内置函数始终返回0
or False
对于虚假和1
or True
为真,除非另有说明。 (重要的例外:布尔运算or
and and
始终返回其操作数之一。)
正如您所看到的,您对操作的看法是正确的内置函数但看到重要例外部分,很好地说明了布尔运算符将返回其操作数之一.
现在,它们能返回什么几乎不取决于操作员的短路逻辑。为了or
运算符,它将返回第一个truthy表达式中的值,因为当它找到一个时,整个表达式为真。如果每个操作数都是falsey, or
将返回最后一个操作数,这意味着它迭代了每个操作数,但无法找到真实的操作数。
For and
运算符,如果表达式为真,则返回最后一个操作数,如果表达式为假,则返回第一个假操作数。您可以阅读更多有关维基百科页面上的短路评估 http://en.wikipedia.org/wiki/Short-circuit_evaluation.
你的问题里举了很多例子,我们来分析一下:
>>> 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()
你可以做单行:
var = var or generate_name()
Since None
是一个假值,or
将继续搜索并评估第二个操作数,即调用最终返回生成名称的函数。这是一个非常愚蠢的例子,我见过这种风格的更好用法(尽管不是在 Python 中)。我现在无法举出更好的例子。您还可以看看这个问题,关于该主题有非常有用的答案:Python 支持短路吗? https://stackoverflow.com/questions/2580136/does-python-support-short-circuiting
最后但并非最不重要的一点是,这与静态类型、鸭子类型、动态、解释、编译等任何语言无关。这只是一种语言功能,可能会派上用场,而且很常见,因为我能想到的几乎每种编程语言都提供了此功能。
希望这可以帮助!