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

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

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

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值