is 除了保持代码的可读性之外,按照 PEP8 的建议,也经常用来比较单例对象,最常见的就是 if node is None: 了
了解以上内容,其实可以尝试回答一下比较诡异的一个问题了:
1
2
3
4
5
6
In [1]: a =420In [2]: b =420In [3]: a is b # shit happensOut[3]: FalseIn [4]: a == b
Out[4]: True
其实是 Python 的实现上的一个优化
首先 Python 已经没有 int 类型了,使用的都是 long 型,相比于原来的 int 类型,占用了 2 倍的空间
所以对于使用比较频繁的比较小的整数,做成了单例的形式。
可以参考 CPython longobject 的实现:
1
2
3
4
5
6
7
8
9
10
11
12
13
#ifndef NSMALLPOSINTS
#define NSMALLPOSINTS 257
#endif
#ifndef NSMALLNEGINTS
#define NSMALLNEGINTS 5
#endif
#if NSMALLNEGINTS + NSMALLPOSINTS > 0
/* Small integers are preallocated in this array so that they
can be shared.
The integers that are preallocated are those in the range
-NSMALLNEGINTS (inclusive) to NSMALLPOSINTS (not inclusive).
*/static PyLongObject small_ints[NSMALLNEGINTS + NSMALLPOSINTS];
[-5, 257) 范围内的整数,内存中只会有一份,不会重复分配内存
对于之前的测试代码,a 与 b 已经超出范围,所以占用了不同的内存地址,is 判断为 False;
但是 __eq__ 实现中,比较的是值的相等性,判断为 True