What is the difference between “ is None ” and “ =

2019-01-01 10:15发布

I recently came across this syntax, I am unaware of the difference.

I would appreciate it if someone could tell me the difference.

标签: python jython
4条回答
唯独是你
2楼-- · 2019-01-01 10:59

The answer is explained here.

To quote:

A class is free to implement comparison any way it chooses, and it can choose to make comparison against None mean something (which actually makes sense; if someone told you to implement the None object from scratch, how else would you get it to compare True against itself?).

Practically-speaking, there is not much difference since custom comparison operators are rare. But you should use is None as a general rule.

查看更多
心情的温度
3楼-- · 2019-01-01 11:04
class Foo:
    def __eq__(self,other):
        return True
foo=Foo()

print(foo==None)
# True

print(foo is None)
# False
查看更多
宁负流年不负卿
4楼-- · 2019-01-01 11:06

In this case, they are the same. None is a singleton object (there only ever exists one None).

is checks to see if the object is the same object, while == just checks if they are equivalent.

For example:

p = [1]
q = [1]
p is q # False because they are not the same actual object
p == q # True because they are equivalent

But since there is only one None, they will always be the same, and is will return True.

p = None
q = None
p is q # True because they are both pointing to the same "None"
查看更多
浮光初槿花落
5楼-- · 2019-01-01 11:08

If you use numpy,

if np.zeros(3)==None: pass

will give you error when numpy does elementwise comparison

查看更多
登录 后发表回答