【问题标题】:Comparing multiple values to None将多个值与无进行比较
【发布时间】:2020-08-14 15:38:47
【问题描述】:

下一段代码是如何工作的?

a = None
b = None
print(a == b) # True
print(a == b is None) # also True

第一个打印很明显,None == None,但是,这是我不明白的第二个打印。我可以想到两种解释方式:

  1. (a == b) is None,但这应该(并且确实)给我们 False,因为 True 不是 None
  2. a == (b is None),这也是 False,因为 b is None 是 True 而 None != True

所以,我无法想象 Python 是如何在此语句中获得 True 的。

【问题讨论】:

标签: python compare interpreter nonetype


【解决方案1】:

Python 中的比较链。

a==b is None 表示(a==b) and (b is None)

见https://docs.python.org/3/reference/expressions.html#comparisons

【讨论】:

    猜你喜欢
    • 2019-04-06
    • 1970-01-01
    • 2018-05-29
    • 1970-01-01
    • 2015-12-21
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多