Python 中的 is 和 ==
今天聊一下Python中的 is 和 == 运算符的区别、
is和==都是对对象进行比较判断作用的
下面举例子看看 is 和 == 在输出上有什么不同
In [1]: a = 'hello'
In [2]: b = 'hello'
In [3]: print(a == b)
True
In [4]: print(a is b)
True
In [5]: a = 'hello world'
In [6]: b = 'hello world'
In [7]: print(a == b)
True
In [8]: print(a is b)
False
In [9]: a = [1, 2, 3]
In [10]: b = [1, 2, 3]
In [11]: print(a == b)
True
In [12]: print(a is b)
False
In [13]: a = [1, 2, 3]
In [14]: b = a
In [15]: print(a == b)
True
In [16]: print(a is b)
True
- is 表示的是对象标示符是否一致,是比较两个对象在内存中的地址是否一样,
而 == 是用来检查两个对象是否相等。
- a is b 是检查 a 和 b 是否指向同一块内存地址,a == b 是检查两个对象是否相等
一般情况下,a is b 的返回是True的话, a == b的返回也应该是True
-
a is b 相当于检查 id(a) == id(b) ,返回的是a , b 的内存地址
a == b相当于检查
a.__eq__(b)
-
也就是说, python中,is 检查两个对象是否是同一个对象,而 == 检查他们是否相等
这样我们再去输出一下 a 和 b 的id:
In [17]: a = 'hello'
In [18]: b = 'hello'
In [19]: print(id(a))
70178720
In [20]: print(id(b))
70178720
In [21]: a = 'hello world'
In [22]: b = 'hello world'
In [23]: print(id(a))
70237152
In [24]: print(id(b))
70231808
In [26]: a = [1, 2, 3]
In [27]: b = [1, 2, 3]
In [28]: print(id(a))
69913456
In [29]: print(id(b))
69912976
In [30]: a = [1, 2, 3]
In [31]: b = a
In [32]: print(id(a))
69925424
In [33]: print(id(b))
69925424
进行None判断时,为什么使用is None 而不是 == None?
在Python指南中也有写到在使用None进行判断时,要使用is None 而不是 == None
- 空值是Python中的一个特殊值,
数据为空并不代表是空对象
。[],'',(),{}
等都不是None。
In [1]: t = []
In [2]: t is None
Out[2]: False
In [3]: t = None
In [4]: t is None
Out[4]: True
- 一个变量如果是None,它一定和None指向同一个内存地址。
- None是python中的一个特殊的常量,表示一个空的对象。
In [5]: a = None
In [6]: b = None
In [7]: id(a) == id(b)
Out[7]: True
- None和任何对象比较返回值都是False,除了自己。
- 因为上面说过的
==None
背后调用的__eq__()
,而__eq__()
可以被重载。如果重载了,那么返回值就不是False,会产生误解。
In [8]: class test():
...: pass # 不重载情况
...:
In [9]: t = test()
In [10]: t is None
Out[10]: False
In [11]: t == None
Out[11]: False
In [12]: class test():
...: def __eq__(self, other):
...: return True # 重载,返回True
...:
In [13]: t = test()
In [14]: t is None
Out[14]: False
In [15]: t == None
Out[15]: True
- 另外从代码执行效率上来看,
is
is a LOT faster than==
。
In [18]: timeit a is b
10000000 loops, best of 3: 56.8 ns per loop
In [19]: timeit id(a) == id(b)
The slowest run took 5.86 times longer than the fastest. This could mean that an intermediate result is being cached.
1000000 loops, best of 3: 222 ns per loop
网友评论