Python 中的短路技术?
编程新手常犯的一个错误是对布尔运算符的工作方式的误解,这源于 Python 解释器读取这些表达式的方式。例如,在最初了解"and"和"or"语句后,人们可能会认为表达式 X = (‘x’ or ‘y’) 会检查变量 X 是否等同于字符串"a"或"b"之一。事实并非如此。要理解我的意思,请启动与解释器的交互式会话并输入以下表达式:
>>> 'x' == ('x' 或 'y')
True
>>> 'y' == ('x' 或 'y')
False
>>> 'x' == ('x' and 'y')
False
>>> 'y' == ('x' and 'y')
True
此时,and 和 or 运算符似乎被破坏了。对于前两个表达式,‘x’ 等同于 ‘x’ 或 ‘y’ 不等同于 ‘x’,这毫无意义。此外,‘y’ 等同于 ‘x’ 和 ‘y’ 是毫无意义的。在检查了解释器对布尔运算符的操作后,这些结果实际上正是您所要求的,只是与您认为要求的不一样。
对于或表达式,python 解释器首先采用第一个语句并检查是否为真。当第一个语句为真时,python 将返回该对象的值而不查看第二个参数。这是因为对于或表达式,如果其中一个值为真,则整个表达式为真;并且程序不会查看第二个语句。但是,如果第一个对象值的计算结果为假,python 将检查第二个语句并返回该值。由于前半部分为假,因此后半部分确定表达式的真值。这种“懒惰”解释器方面的这种做法称为"短路",是许多编程语言中评估布尔表达式的常用方法。
同样,对于 and 表达式,python 使用短路技术来加速真值评估。如果第一个语句为假,则整个语句必定为假,并返回该对象值 (false),否则,如果第一个值为真,则检查第二个值并返回该值。让我们来看看解释器在执行代码时"看到"了什么
第一种情况
'x' == ('x' or 'y') # Look at parentheses first, so evaluates "('x' or 'y")"
# 'x' is a nonempty string, so the first value is True
>>> 'x' == 'x' # the string 'x' is equivalent to the string 'x' , so our expression is True
True
第二种情况
'y' == ('x' or 'y')# Look at parentheses first, so evaluates expression "('x' or 'y')"
# 'x' is a nonempty string, so the first value is True
#Return that first value : 'x'
'y' == 'x'# the string 'y' is not equivalent to the string 'x', so the expression is False
Third Case
>>> 'x' == ('x' and 'y')# Look at parentheses first, so evaluate expression "('x' and 'y')"
#'x' is a nonempty string, so the first value is True, examine second value
# 'y' is a nonempty string, so second value is True
#Return that second value as result of whole expression: 'y'
>>> 'x' == 'y'# the string 'x' is not equivalent to the string 'y', so expression is False
False
第四种情况
>>> 'y' == ('x' and 'y')# Look at parenthese first, so evaluates expression "('x' and 'y')"
True
# 'x' is a nonempty string, so the first value is True, examine second value
# 'y' is a nonempty string, so second value is True
# Return that second value as result of whole expression: 'y'
>>> 'y' == 'y'# the string 'y' is equivalent to the string 'y', so expression is True
True
短路求值是指在求值布尔表达式(如AND和OR)时,只要找到第一个满足或否定表达式的条件,就可以停止。
官方文档对短路的解释:
| 操作 | 结果 | 描述 |
|---|---|---|
| x or y | 如果x为假,则y否则x | 仅当第一个参数为假时才求值第二个参数(y) |
| x and y | 如果x为假,则x否则y | 仅求值第二个参数(y)如果第一个 (x) 为 True |
| 非 x | 如果 x 为 false,则为 True,否则为 False | Not 的优先级低于非布尔运算符 |
相关文章
有用资源
python 参考教程 - 该教程包含有关 python 的更多信息:https://www.cainiaomax.com/python/

