我正在浏览 LPTHW,我遇到了一些我无法理解的事情。您什么时候会希望 boolean 值 and
或 or
返回 boolean 值以外的值? LPTHW 文本指出所有语言如 python 都有这种行为。他是指解释型语言与编译型语言,还是鸭子类型语言与静态类型语言?
我运行了以下代码:
>>> False and 1
False
>>> True and 1
1
>>> 1 and False
False
>>> 1 and True
True
>>> True and 121
121
>>> False or 1
1
>>> False or 112
112
>>> False or "Khadijah"
'Khadijah'
>>> True and 'Khadijah'
'Khadijah'
>>> False or 'b'
'b'
>>> b = (1, 2, "K")
>>> b
(1, 2, 'K')
>>> False or b
(1, 2, 'K')
>>>
请帮助我了解这里发生了什么。
根据文档:http://docs.python.org/2/library/stdtypes.html
具有 boolean 结果的操作和内置函数总是返回 0
或 False
为 false 和 1
或 True
为真,除非另有说明。 (重要的异常(exception): boolean 运算 or
和 and
总是返回它们的操作数之一。)
根据 LPTHW:http://learnpythonthehardway.org/book/ex28.html
为什么 “test”和“test”
返回“test”或 1 和 1
返回 1 而不是 True?
Python 和许多类似的语言将操作数之一返回到它们的 boolean 表达式,而不仅仅是 True 或 False。这意味着如果您执行 False 和 1,您将获得第一个操作数 (False),但如果您执行 True 和 1,您将获得第二个 (1)。玩一下这个。
最佳答案
我认为您对文档所说的内容有些困惑。看看这两个文档部分:Truth Value Testing and Boolean Operators .引用第一节的最后一段:
Operations and built-in functions that have a Boolean result always return
0
orFalse
for false and1
orTrue
for true, unless otherwise stated. (Important exception: the Boolean operationsor
andand
always return one of their operands.)
如您所见,您对操作和内置函数的看法是正确的,但请参阅重要异常部分, boolean 运算符将返回他们的操作数之一。
现在,他们可以返回什么几乎不取决于运营商的短路逻辑。对于 或
运算符,它将返回表达式中的第一个 truthy 值,因为当它找到一个值时,整个表达式为真。如果每个操作数都是 falsey,or
将返回最后一个操作数,这意味着它遍历了每个操作数而无法找到一个真实的操作数。
对于and
运算符,如果表达式为真,则返回最后一个操作数,如果表达式为假,则返回第一个假操作数。您可以阅读更多关于 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
是一个假值,or
将继续搜索并评估第二个操作数,即调用最终返回生成名称的函数。这是一个非常愚蠢的例子,我见过这种风格的更好用法(虽然不是在 Python 中)。我现在想不出更好的例子。您也可以看看这个问题,关于这个主题有非常有用的答案:Does Python support short-circuiting?
最后但并非最不重要的一点是,这与静态类型、鸭子类型、动态、解释、编译以及任何语言无关。这只是一种语言功能,可能会派上用场,而且非常普遍,因为我能想到的几乎所有编程语言都提供此功能。
希望这对您有所帮助!
关于python - 为什么 'and' 和 'or' 在 Python 中返回操作数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22598547/