如果断言语句包含 'if .... else ....',您如何解释它?
How do you interpret an assert statement if it contains an 'if .... else ....'?
编辑:它回答了,我不明白什么是三元运算符。
对于未来有类似问题的人:https://book.pythontips.com/en/latest/ternary_operators.html
我正在研究 python 中的 'assert' 语句,我不明白下面的句子。
assert .. if ... else ... and ...
所以如果我理解正确的话,如果你想测试一个 'if else ' 语句,你必须使用上面的方法。您必须在“if”语句之后立即插入以下内容:assert (P1 if E else P2) and E
例如
assert (y == builtins.max(x, y) if x < y else x == builtins.max(x, y)) and x < y
如果理解assert y == builtins.max(x,y)
它只是检查条件是否为真,当它不为真时它 return 是一个断言错误。但是在以下情况下:
assert (y == builtins.max(x, y) if x < y else x == builtins.max(x, y)) and x < y
我不知道发生了什么。它显然也总是 return 是真的。但我什至无法猜测到底发生了什么。我查看了 assert 语句的作用,它唯一做的是:assert <condition>,<error message>
所以检查条件并可能 return 一条错误消息。但是我不明白 ... if ... else ... and ...
是一个条件。我理解 and
,但在那种情况下,您究竟如何解释 if else
部分?
我真的不明白我不明白的东西。这可能是非常微不足道的。希望有人能帮助我。抱歉我的拼写错误。
编辑:它回答了,我不明白什么是三元运算符。
对于未来有类似问题的人:https://book.pythontips.com/en/latest/ternary_operators.html
这里发生的是三元的断言。
这个:
(y == builtins.max(x, y) if x < y else x == builtins.max(x, y)) and x < y
概念上是:
A if cond else B # and cond2, but we'll come to that
哪个先评估为 A 或 B。然后我们断言,所以
assert A if cond else B
与
相同
x = A if cond else B
assert x
这个特殊的三元并不简单。相当于:
if x < y:
res = y == builtins.max(x, y)
else:
res = x == builtins.max(x,y)
assert res and x < y
恕我直言,这不是很清楚。无论如何这很有趣,因为在大多数情况下你可以只做 max()
而不是 builtins.max()
。也许它属于测试,或者 max()
被(不明智地)覆盖的上下文? [这么一想,大概是对builtins.max
的考验吧?]
参考资料
有关 python 的三元结构的更多信息,请参见例如this question.
编辑:它回答了,我不明白什么是三元运算符。 对于未来有类似问题的人:https://book.pythontips.com/en/latest/ternary_operators.html
我正在研究 python 中的 'assert' 语句,我不明白下面的句子。
assert .. if ... else ... and ...
所以如果我理解正确的话,如果你想测试一个 'if else ' 语句,你必须使用上面的方法。您必须在“if”语句之后立即插入以下内容:assert (P1 if E else P2) and E
例如
assert (y == builtins.max(x, y) if x < y else x == builtins.max(x, y)) and x < y
如果理解assert y == builtins.max(x,y)
它只是检查条件是否为真,当它不为真时它 return 是一个断言错误。但是在以下情况下:
assert (y == builtins.max(x, y) if x < y else x == builtins.max(x, y)) and x < y
我不知道发生了什么。它显然也总是 return 是真的。但我什至无法猜测到底发生了什么。我查看了 assert 语句的作用,它唯一做的是:assert <condition>,<error message>
所以检查条件并可能 return 一条错误消息。但是我不明白 ... if ... else ... and ...
是一个条件。我理解 and
,但在那种情况下,您究竟如何解释 if else
部分?
我真的不明白我不明白的东西。这可能是非常微不足道的。希望有人能帮助我。抱歉我的拼写错误。
编辑:它回答了,我不明白什么是三元运算符。 对于未来有类似问题的人:https://book.pythontips.com/en/latest/ternary_operators.html
这里发生的是三元的断言。
这个:
(y == builtins.max(x, y) if x < y else x == builtins.max(x, y)) and x < y
概念上是:
A if cond else B # and cond2, but we'll come to that
哪个先评估为 A 或 B。然后我们断言,所以
assert A if cond else B
与
相同x = A if cond else B
assert x
这个特殊的三元并不简单。相当于:
if x < y:
res = y == builtins.max(x, y)
else:
res = x == builtins.max(x,y)
assert res and x < y
恕我直言,这不是很清楚。无论如何这很有趣,因为在大多数情况下你可以只做 max()
而不是 builtins.max()
。也许它属于测试,或者 max()
被(不明智地)覆盖的上下文? [这么一想,大概是对builtins.max
的考验吧?]
参考资料
有关 python 的三元结构的更多信息,请参见例如this question.