Python的is和==区别(整理)

来源:互联网 发布:矩阵的秩ppt 编辑:程序博客网 时间:2024/06/08 05:41

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 = name1print(name1 is name2, name1  == name2)print(name1 is name3, name1  == name3)

结果:

False FalseTrue 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: False250: True251: True252: True253: True254: True255: True256: True257: False258: False259: False

参考:Is there a difference between == and is in Python?

原创粉丝点击