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

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

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


也举个例子

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

a = A()
print(a == a)   #False
print(a is a)   #True

http://blog.csdn.net/imzoer/article/details/8637408


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


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


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
【热门文章】
【热门文章】