前段时间,有个新手问我 这样一个问题 python 的is 和 == 的区别。对于pyhton来说 == 其实调用的是魔术方法 __eq__,
而 == 调用的是 __cmp__。 拿代码举个例子
class A(object): def __init__(self, value): self.value = value def __eq__(self, other): return self.value== other.value def __cmp__(self, other): return id(self) == id(other) a = A(1) b = A(1) print a==b #True print a is b #False
再深入 说一下 python 对于小整数的处理机制,python 将 -127 到128这个区间的数都缓存了一份,即这些对象在python虚拟机里是单例的。任何时候比较都是True
a = 10
b=10
a is b #True
a = 10.0
b = 10.0
a is b # False
a = 1000
b = 1000
a is b #False