python 运算符 is 、is not 、== 、!=

  • 实验环境:Python 3.7.5,macOS Mojave 10.14.6

在介绍以上运算符之前,需要介绍一个函数id(),其作用是获取对象的内存地址,例如:

>>> a = 1
>>> id(a)
4414246672		#内存地址

再说说运算符is、==的区别

  • is is an identity test. It checks whether the right hand side and the left hand side are the very same object. No methodcalls are done, objects can’t influence the is operation.
  • == is an equality test. It checks whether the right hand side and the left hand side are equal objects (according to their eq or cmp methods.)
  • 也就是说,is 判断的是两个变量是否指向同一个对象,即,地址是否相同,可以通过id()函数判断;== 判断两个变量的值是否相等。如果is 为 true,==也为 true;反之,不能保证。
  • 同理,is not 判断的是两个变量是否指向不同的对象;!= 判断两个变量的值是否不相等。

在使用以上运算符的过程中,有几种情况是需要注意的:

1. 数值变量

a. 整型

>>> a = 1
>>> b = 1
>>> a is b
True
>>> a == b
True

b. 浮点型

>>> a = 2.1
>>> b = 2.1
>>> a is b
False
>>> a == b
True

2. 字符串

>>> a="abc"
>>> b="abc"
>>> a is b
True
>>> a==b
True

3. 列表(list)、元组(tuple)、字典(dict)、集合(set)

a. list

>>> a=[1,2]
>>> b=[1,2]
>>> a is b
False
>>> a == b
True

b. tuple

>>> a=(1,3)
>>> b=(1,3)
>>> a is b
False
>>> a == b
True

c. dict

>>> a={"a":1,"b":2}
>>> b={"a":1,"b":2}
>>> a is b
False
>>> a == b
True

d. set

>>> d = set()	# 空集合,不能使用 d={}
>>> d = {}		# 空字典
<class 'dict'>
>>> a={1,2,3}	# or a = set((1,2,3))
>>> type(a)
<class 'set'>
>>> b={1,2,3}
>>> a is b
False
>>> a == b
True

4. 对象赋值

>>> a = 1.2
>>> b = a	# 指向同一内存地址
>>> a is b
True
>>> a == b
True

总结

从以上实例的运行结果中,可以发现几个结论:

  • 数值变量的判断,整型是一样的;但是,浮点型不一样
  • 字符串的判断,结果相同
  • 列表(list)、元组(tuple)、字典(dict)、集合(set),结果不一样

以上结论是基于独立对象之间的判断,对象之间没有赋值。若对象之间有赋值,结论会有不同,见4.对象赋值,两种判断结果是相同的,实例中只用浮点数演示,其他类型的判断结果也是一样的,可自行测试。

猜你喜欢

转载自blog.csdn.net/zxcasd11/article/details/103892867