为什么"20000 is 20000"的结果为True? [英] Why does '20000 is 20000' result in True?

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

问题描述

is测试2个引用是否指向同一对象. 内部缓存的数字介于-5和256之间,因此:

is in Python tests if 2 references point to the same object. Numbers between -5 and 256 are cached internally so:

a = 10
b = 10
a is b # Results in True

这如何解释以下内容:

20000 is 20000 # Results in True

两个数字均大于256. 这两个整数不应该是2个不同的对象吗?

Both numbers are above 256. Should not the 2 integers be 2 distinct objects?

推荐答案

Python解释器看到您正在重新使用不可变的对象,因此不必费心创建两个对象:

The Python interpreter sees you are re-using a immutable object, so it doesn't bother to create two:

>>> import dis
>>> dis.dis(compile('20000 is 20000', '', 'exec'))
  1           0 LOAD_CONST               0 (20000)
              3 LOAD_CONST               0 (20000)
              6 COMPARE_OP               8 (is)
              9 POP_TOP
             10 LOAD_CONST               1 (None)
             13 RETURN_VALUE

请注意两个LOAD_CONST操作码,它们都在索引0处加载常量:

Note the two LOAD_CONST opcodes, they both load the constant at index 0:

>>> compile('20000 is 20000', '', 'exec').co_consts
(20000, None)

在交互式解释器中,Python限于必须分别编译您输入的每个(简单或复合)语句,因此它不能在不同的语句之间重用这些常量.

In the interactive interpreter Python is limited to having to compile each (simple or compound) statement you enter separately, so it can't reuse these constants across different statements.

但是在一个函数对象中,即使您多次使用相同的int常量,也肯定只会创建一个这样的整数对象.这同样适用于在模块级别上运行的任何代码(因此在函数或类定义之外);这些都以相同的代码对象常量结尾.

But within a function object it certainly would only create one such integer object, even if you used the same int literal more than once. The same applies to any code run at the module level (so outside of functions or class definitions); those all end up in the same code object constants too.

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

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