《Python核心编程》中 `type(a)== type(b)` 与 `type(a) is type(b)`的区别

type(a)== type(b)type(a) is type(b)的区别,为什么用后者不用前者呢?

阅读 6.4k
5 个回答

is check 两边的值是否为同一对象. == 实际上call了左值的__eq__(), 然后pass给右值.

== 是比大小
is 是找地址
找地址更快、高效

type(a) == type(b) : a,b继承的类 (类也是基类的实例) 值相等 就像:

c = [1,2,3]
d = [1,2,3]
c == d
>>> True
c is d
>>> false

type(a) == type(b): a,b继承的类 是同一个实例(内存地址相同)就像

c = 1
d = 1
c == d
>>> True
c is d
>>> True

也举个例子

class A(object):
    def __eq__(self, other):
        return False

a = A()
print(a == a)   #False
print(a is a)   #True
撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题