【发布时间】:2019-01-17 22:07:13
【问题描述】:
我无法在 Python 中生成显示布尔运算符优先规则与短路评估相结合的示例。我可以使用以下方式显示运算符优先级:
print(1 or 0 and 0) # Returns 1 because `or` is evaluated 2nd.
但是当我把它改成这个时,短路的问题就出现了:
def yay(): print('yay'); return True
def nay(): print('nay')
def nope(): print('nope')
print(yay() or nay() and nope()) # Prints "yay\nTrue"
当or 之前的表达式为True 时,对于 4 种可能性中的每一种,它都是唯一评估的表达式。如果运算符优先级有效,则应打印 "nay\nnope\nyay\nTrue" 或 "nay\nyay\nTrue",并进行短路,因为应首先评估 and。
从这个例子中想到的是,Python 从左到右读取布尔表达式,并在结果已知时结束它,而不管运算符优先级如何。
我的错误在哪里或我错过了什么?请举一个例子,其中and 被评估为第一个,这不是因为代码从左到右解释。
【问题讨论】:
-
请注意,运算符优先级与评估顺序不同。
标签: python boolean-logic operator-precedence short-circuiting