为什么`None is None is None` 返回 True? [英] Why does `None is None is None` return True?

查看:77
本文介绍了为什么`None is None is None` 返回 True?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

今天,在一次采访中,CTO 问了我一个看起来很简单的问题,

这个语句返回什么?:

None is None is None

我认为 Python 执行了第一个操作 None is None 并且会返回 True.之后,它会比较 True is None 将返回 False.但是,令我惊讶的是,正确答案是 True.我试图找到这个问题的答案,但经过几天的搜索,我什么也没找到.有人可以解释为什么会发生这种情况吗?

解决方案

字节码显示这里进行了两次比较,中间被复制了:

<预><代码>>>>导入文件>>>定义一个():... return None is None is None...>>>dis.dis(a)2 0 LOAD_CONST 0(无)3 LOAD_CONST 0(无)6 DUP_TOP7 ROT_THREE8 COMPARE_OP 8 (是)11 JUMP_IF_FALSE_OR_POP 2114 LOAD_CONST 0 (无)17 COMPARE_OP 8 (是)20 RETURN_VALUE>>21 ROT_TWO22 POP_TOP23 RETURN_VALUE

比较文档中所述,这是因为这些运算符串联起来.

a op b op c 将被翻译成 a op b and b op c (注意 b 在字节码中重复,如图所示以上)

Today, in an interview, the CTO asked me what looks like an easy question,

What does this statement return ? :

None is None is None

I thought Python executed the first operation None is None and would return True. After that, it would compare True is None which would return False. But, to my surprise, the right answer is True. I am trying to find answer to this question, but after a couple of days searching I didn't find anything. Can someone explain why this happens?

解决方案

The bytecode shows that two comparisons are being performed here with the middle being duplicated:

>>> import dis
>>> def a():
...     return None is None is None
... 
>>> dis.dis(a)
  2           0 LOAD_CONST               0 (None)
              3 LOAD_CONST               0 (None)
              6 DUP_TOP
              7 ROT_THREE
              8 COMPARE_OP               8 (is)
             11 JUMP_IF_FALSE_OR_POP    21
             14 LOAD_CONST               0 (None)
             17 COMPARE_OP               8 (is)
             20 RETURN_VALUE
        >>   21 ROT_TWO
             22 POP_TOP
             23 RETURN_VALUE

As stated in the docs for comparisons this is because these operators chain together.

a op b op c will be translated to a op b and b op c (note b is duplicated in the bytecode as shown above)

这篇关于为什么`None is None is None` 返回 True?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆