Python中Is和==的功能都是用来比较两个元素是否相同,但是在具体对比的内容上面还是有一些区分,虽然这一个概念比较简单,但是还是作为笔记记录下来方便以后查阅。
Python的对象有三个基本要素:唯一标识码(id),对象值(value)和对象类型(type)。python也有各自的方法拿到这三个要素的内容,比如定义了一个对象a,id(a)就可以拿到a的标识码,type(a)可以返回对象a的类型。
所以在比较的时候,is比较的是这两个元素的唯一标识码是否相同,而==比较的是这两个的元素的内容是否相同。用下面的代码来展示出它们之间的区别:
class testClass():
def __init__(self, para1):
contentA = para1
def testFun1(self):
print(self.contentA)
def test1():
a=1
b=1
print('a=1,b=1 ==> a==b:',a == b)
print('a=1,b=1 ==> a is b:', a is b)
print('a=1,b=1 ==> id(a)=',id(a))
print('a=1,b=1 ==> id(b)=', id(b))
a = '1'
b = '1'
print('a=\'1\',b=\'1\' ==> a==b:', a == b)
print('a=\'1\',b=\'1\' ==> a is b:', a is b)
print('a=\'1\',b=\'1\' ==> id(a)=', id(a))
print('a=\'1\',b=\'1\' ==> id(b)=', id(b))
a = [1]
b = [1]
print('a=[1],b=[1] ==> a==b:', a == b)
print('a=[1],b=[1] ==> a is b:', a is b)
print('a=[1],b=[1] ==> id(a)=', id(a))
print('a=[1],b=[1] ==> id(b)=', id(b))
a = (1,)
b = (1,)
print('a=(1,),b=(1,) ==> a==b:', a == b)
print('a=(1,),b=(1,) ==> a is b:', a is b)
print('a=(1,),b=(1,) ==> id(a)=', id(a))
print('a=(1,),b=(1,) ==> id(b)=', id(b))
a = {'a1':1}
b = {'a1':1}
print('a={\'a1\':1},b={\'a1\':1} ==> a==b:', a == b)
print('a={\'a1\':1},b={\'a1\':1} ==> a is b:', a is b)
print('a={\'a1\':1},b={\'a1\':1} ==> id(a)=', id(a))
print('a={\'a1\':1},b={\'a1\':1} ==> id(b)=', id(b))
a = testClass('1')
b = testClass('1')
print('a=testClass(\'1\'),b=testClass(\'1\') ==> a==b:', a == b)
print('a=testClass(\'1\'),b=testClass(\'1\') ==> a is b:', a is b)
print('a=testClass(\'1\'),b=testClass(\'1\') ==> id(a)=', id(a))
print('a=testClass(\'1\'),b=testClass(\'1\') ==> id(b)=', id(b))
运行结果:
a=1,b=1 ==> a==b: True
a=1,b=1 ==> a is b: True
a=1,b=1 ==> id(a)= 1736063232
a=1,b=1 ==> id(b)= 1736063232
a='1',b='1' ==> a==b: True
a='1',b='1' ==> a is b: True
a='1',b='1' ==> id(a)= 1949312
a='1',b='1' ==> id(b)= 1949312
a=[1],b=[1] ==> a==b: True
a=[1],b=[1] ==> a is b: False
a=[1],b=[1] ==> id(a)= 132389344
a=[1],b=[1] ==> id(b)= 132389904
a=(1,),b=(1,) ==> a==b: True
a=(1,),b=(1,) ==> a is b: True
a=(1,),b=(1,) ==> id(a)= 3256928
a=(1,),b=(1,) ==> id(b)= 3256928
a={'a1':1},b={'a1':1} ==> a==b: True
a={'a1':1},b={'a1':1} ==> a is b: False
a={'a1':1},b={'a1':1} ==> id(a)= 3237712
a={'a1':1},b={'a1':1} ==> id(b)= 3237376
a=testClass('1'),b=testClass('1') ==> a==b: False
a=testClass('1'),b=testClass('1') ==> a is b: False
a=testClass('1'),b=testClass('1') ==> id(a)= 3202160
a=testClass('1'),b=testClass('1') ==> id(b)= 3202256