【问题标题】:Python checking condition and safety in same if statementPython在相同的if语句中检查条件和安全性
【发布时间】:2020-05-29 19:08:49
【问题描述】:

我一直在写一些python代码,如果对象为None,则我有一个条件,如果它没有获取对象属性并检查它,则返回。这是一个示例代码:

b = None
if b is None or b.property == "something":
    print("yay")

当上面运行的代码打印AttributeError: 'NoneType' object has no attribute 'property' 时下面的代码打印相同的结果。

b = None
if b.property == "something" or b is None:
    print("yay")

问题: 假设在评估其中一个为真后,if 子句中有许多or 检查,其他条件可以被绕过,因为结果将是真的,所以它浪费了#compute power。 如果任何条件为 0 结果为零,则同样可以应用于 and 运算符。那么为什么上面的示例会触发 exception

【问题讨论】:

    标签: python logic logical-operators


    【解决方案1】:

    我正在写我的问题而不是它击中我。无论如何我也会为我的问题留下解决方案。

    if (b is None) or b.property == "something":
        print("yay")
    

    There is a natural order to this world! =)

    【讨论】:

    • 你也可以只做“if b or b.property=='something'”。
    【解决方案2】:

    我无法重现错误。

    >>> b = None
    >>> b is None or b.property == 'something'
    True
    

    但是,您可能有兴趣知道or 关键字不一定返回TrueFalse;相反,给定表达式a or b,如果a 为真,则返回a,否则返回b,不管它是布尔值。如果操作顺序不同,我们会收到您描述的错误:

    >>> b is (None or b.property) == 'something'
    AttributeError: 'NoneType' object has no attribute 'property'
    

    【讨论】:

      猜你喜欢
      • 2018-04-16
      • 2017-12-08
      • 1970-01-01
      • 1970-01-01
      • 2012-12-13
      • 1970-01-01
      • 1970-01-01
      • 2022-07-07
      • 2022-11-01
      相关资源
      最近更新 更多