is和==的区别
解释1
==
is for value equality. Use it when you would like to know if two objects have the same value.is
is for reference equality. Use it when you would like to know if two references refer to the same object.
解释2
is
: if two variables point to the same object.==
: if the objects referred to by the variables are equal.
解释3
python中的每个对象都有三种属性:id
, value
, type
. 不同对象实例的id
一定是不同的,可以把id
看做是和内存地址一一对应的。而value
只是检查两个变量的内容是否相等。
解释4
==
会调用对应类里的__eq__()
函数。例如:
class Name(object):
def __eq__(self, other):
print('__eq__() is called.')
name1 = Name()
name2 = Name()
print(name1 == name2)
结果:
__eq__() is called.
None # __eq__()里面没有return,所以==的结果为None
然而如果没有重写__eq__()
函数,我猜测就会去调用is
的操作。例如:
class Name(object):
pass
# 创建两个不同的Name对象
name1 = Name()
name2 = Name()
# 让name3和name1指向同一个Name对象
name3 = name1
print(name1 is name2, name1 == name2)
print(name1 is name3, name1 == name3)
结果:
False False
True True
例外情况:
This is inconsistent with the earlier result. It turns out the reference implementation of Python caches integer objects in the range -5~256 as singleton instances for performance reasons.
Example:
for i in range(1, 10):
a = -i
is_res = a is int(str(a))
print("%i: %s" % (a, is_res))
print()
for i in range(250, 260):
a = i
is_res = a is int(str(a))
print("%i: %s" % (a, is_res))
results:
-1: True
-2: True
-3: True
-4: True
-5: True
-6: False
-7: False
-8: False
-9: False
250: True
251: True
252: True
253: True
254: True
255: True
256: True
257: False
258: False
259: False