为什么'和' &'or' 在 Python 中返回操作数?

2022-01-19 00:00:00 python boolean operands

问题描述

我正在经历 LPTHW,但遇到了一些我无法理解的事情.什么时候你希望你的布尔值 andor 返回布尔值以外的东西?LPTHW 文本指出,像 python 这样的所有语言都有这种行为.他是指解释型语言还是编译型语言,还是鸭子类型语言和静态类型语言?

I'm going through the LPTHW and I came across something I cannot understand. When will it ever be the case that you want your boolean and or or to return something other than the boolean? The LPTHW text states that all languages like python have this behavior. Would he mean interpreted vs. compiled languages or duck typed vs static typed languages?

我运行了以下代码:

>>> 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')
>>> 

请帮助我了解这里发生了什么.

Please help me understand whats going on here.

根据文档:http://docs.python.org/2/library/stdtypes.html

具有布尔结果的操作和内置函数总是返回 0False 为 false 和 1True 为真,除非另有说明.(重要的例外:布尔运算 orand 总是返回它们的操作数之一.)

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.)

根据 LPTHW:http://learnpythonthehardway.org/book/ex28.html为什么 "test" 和 "test" 返回 "test" 或 1 and 1 返回 1 而不是 True?Python 和许多类似的语言将操作数之一返回到其布尔表达式,而不仅仅是 True 或 False.这意味着,如果您执行 False and 1,您将获得第一个操作数 (False),但如果您执行 True and 1,您将获得第二个操作数 (1).玩一下这个.

According to LPTHW: http://learnpythonthehardway.org/book/ex28.html Why does "test" and "test" return "test" or 1 and 1 return 1 instead of True? Python and many languages like it return one of the operands to their boolean expressions rather than just True or False. This means that if you did False and 1 you get the first operand (False) but if you do True and 1 your get the second (1). Play with this a bit.


解决方案

我认为您对文档所说的内容感到困惑.看看这两个文档部分:真值测试和布尔运算符.引用第一部分的最后一段:

I think you're somehow confused about what the docs says. Take a look at these two docs sections: Truth Value Testing and Boolean Operators. To quote the last paragraph on the fist section:

具有布尔结果的操作和内置函数总是返回 0False 对于 false 和 1True 为真,除非另有说明.(重要的例外:布尔运算 orand 总是返回它们的操作数之一.)

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.)

如您所见,您对操作和 内置函数 是正确的,但请参阅 重要异常 部分,很好地说明了布尔运算符 将返回其中一个操作数.

As you can see, you're right about operations and built-in functions but see the Important exception part, it is well stated that the Boolean operators will return one of their operands.

现在,它们能返回什么几乎不取决于操作员的短路逻辑.对于 or 运算符,它将返回表达式中的第一个 truthy 值,因为当它找到一个时,整个表达式为 true.如果每个操作数都为 falsey, 将返回最后一个操作数,这意味着它遍历了每个操作数,但无法找到真实的操作数.

Now, what they can return depends hardly on the operator's short circuit logic. For or operator, it will return the first truthy value in the expression, since when it finds one, the whole expression is true. In case of every operand being falsey, or will return the last operand, meaning that it iterated over every one of them not being able to find a truthy one.

对于and运算符,如果表达式为真,则返回最后一个操作数,如果表达式为假,则返回第一个假操作数.您可以在维基百科页面上的短路评估阅读更多信息.

For and operator, if the expression is true, it will return the last operand, if the expression is false, it will return the first falsey operand. You can read more about Short Circuit Evaluation at the Wikipedia Page.

你的问题有很多例子,我们来分析一下:

You have a lot of examples in your question, let's analyze some of them:

>>> 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'

我认为这应该说明问题.为了帮助您进一步了解这为何有用,请考虑以下示例:

I think this should make a point. To help you further understand why this is useful, consider the following example:

你有一个随机生成名字的函数

You have a function that randomly generate names

import random

def generate_name():
    return random.choice(['John', 'Carl', 'Tiffany'])

你有一个变量,你不知道它是否已经分配了一个名称,所以不要这样做:

and you have a variable that you don't know if it has assigned a name yet so instead of doing:

if var is None:
    var = generate_name()

你可以做oneliner:

You can do oneliner:

var = var or generate_name()

由于 None 是一个假值,or 将继续搜索并计算第二个操作数,即调用最终返回生成名称的函数.这是一个非常愚蠢的例子,我见过这种风格的更好用法(虽然不是在 Python 中).我现在想不出更好的例子.你也可以看看这个问题,关于这个话题有非常有用的答案:Does Python support短路了?

Since None is a falsey value, or will continue its search and evaluate second operand, this is, call the function ultimately returning the generated name. This is a very silly example, I have seen better usages (although not in Python) of this kind of style. I couldn't come out with a better example right now. You can also take a look at this questions, there are very useful answers on the topic: Does Python support short-circuiting?

最后但并非最不重要的一点是,这与静态类型、鸭子类型、动态、解释、编译等任何语言无关.这只是一种语言功能,可能会派上用场,而且很常见,因为我能想到的几乎所有编程语言都提供此功能.

Last but not least, this has nothing to do with static typed, duck typed, dynamic, interpreted, compiled, whatever language. It's just a language feature, one that might come handy and that is very common since almost every programming language I can think of provide this feature.

希望这会有所帮助!

相关文章