【问题标题】:How do you interpret an assert statement if it contains an 'if .... else ....'?如果断言语句包含“if .... else ....”,您如何解释它?
【发布时间】:2021-12-25 12:06:30
【问题描述】:

编辑:它的回答,我不明白三元运算符是什么。 对于未来有类似问题的人: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) 它只是检查条件是否为真,当它不为真时,它返回一个断言错误。但是,在以下情况下: assert (y == builtins.max(x, y) if x &lt; y else x == builtins.max(x, y)) and x &lt; y

我不知道发生了什么。它显然也总是返回 true。但我什至无法猜测到底发生了什么。我查看了 assert 语句的作用,它唯一的作用是:assert &lt;condition&gt;,&lt;error message&gt; 所以检查条件并可能返回错误消息。但是我不明白... if ... else ... and ... 是一个条件。我了解and,但您如何准确地解释这种情况下的if else 部分?

我真的不明白我不明白的东西。这可能非常微不足道。希望有人可以帮助我。抱歉我的拼写错误。

编辑:它的回答,我不明白三元运算符是什么。 对于未来有类似问题的人:https://book.pythontips.com/en/latest/ternary_operators.html

【问题讨论】:

    标签: python testing assert


    【解决方案1】:

    这里发生的是三元的断言。

    这个:

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

    【讨论】:

    • 谢谢...我不明白什么是三元运算符。我现在明白声明是什么了。
    • @bananenheld 如果这个答案是 :) 你在哪里找到这个断言顺便说一句?
    猜你喜欢
    • 1970-01-01
    • 2013-03-09
    • 1970-01-01
    • 2022-12-07
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多