Python之 is None VS == None

来源:互联网 发布:js substr 编辑:程序博客网 时间:2024/05/19 22:47

起因是来自于tensorflow即将要改版,对==None也做成elementwise的。具体地,笔者在运行tensorflow得到一下警告:FurtherWarning: comparison to ‘None’ will result in an elementwise object comparison in the future。
所以使得笔者注意到is None和==None还是有区别的,详细内容请参照:http://jaredgrubb.blogspot.com/2009/04/python-is-none-vs-none.html。
简单地说,==操作会调用左操作数的__eq__函数,而这个函数可以被其任意定义。而is操作只是做id比较,并不会被自定义。同时也可以发现is函数是要快于==的,因为不用查找和运行函数。
比如说如下代码

class a:    def __eq__(self,other):        return Trueprint (a()==None)print (a() is None)

打印值为True False。