Python 中的短路技术?
对于编程新手来说,一个常见的错误是对布尔运算符工作方式的误解,这源于 Python 解释器读取这些表达式的机制。例如,在最初学习“and”和“or”语句后,人们可能会假设表达式 X = (‘x’ or ‘y’) 会检查变量 X 是否等效于字符串 ‘a’ 或 ‘b’ 之一。事实并非如此。要理解我想要表达的意思,请启动一个与解释器的交互式会话并输入以下表达式
>>> 'x' == ('x' or 'y')
True
>>> 'y' == ('x' or 'y')
False
>>> 'x' == ('x' and 'y')
False
>>> 'y' == ('x' and 'y')
True此时,and 和 or 运算符似乎坏了。对于前两个表达式,‘x’ 等效于 ‘x’ 或 ‘y’ 不是很合理。此外,‘y’ 等效于 ‘x’ 和 ‘y’ 也没有任何意义。在检查了解释器如何处理布尔运算符之后,这些结果实际上完全符合您的要求,只是与您认为自己所要求的不同。
对于 or 表达式,Python 解释器首先获取第一个语句并检查其是否为真。当第一个语句为真时,Python 会返回该对象的返回值,而无需查看第二个参数。这是因为对于 or 表达式,如果其中一个值为真,则整个表达式为真;并且程序不会查看第二个语句。但是,如果第一个对象的返回值计算结果为假,则 Python 会检查第二个语句并返回该值。由于前半部分为假,因此后半部分决定表达式的真值。解释器这种“懒惰”的行为称为“短路”,是许多编程语言中评估布尔表达式的常用方法。
类似地,对于 and 表达式,Python 使用短路技术来加速真值评估。如果第一个语句为假,则整个表达式必须为假,它会返回该对象的返回值(假),否则,如果第一个值为真,它会检查第二个值并返回该值。让我们看一下解释器在遍历代码时“看到”的内容
第一种情况
'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第三种情况
>>> '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 | 仅当第一个参数(x)为真时才评估第二个参数(y) |
| not x | 如果 x 为假,则为真,否则为假 | not 的优先级低于非布尔运算符 |
广告
数据结构
网络
RDBMS
操作系统
Java
iOS
HTML
CSS
Android
Python
C 编程
C++
C#
MongoDB
MySQL
Javascript
PHP