identity versus equality for None in Python

后端 未结 3 930
遇见更好的自我
遇见更好的自我 2020-12-06 01:01

Various Python guides say to use x is None instead of x == None. Why is that? Equality is used for comparing values, so it seems natural to ask if

3条回答
  •  無奈伤痛
    2020-12-06 01:43

    The reason people use is is because there is no advantage to using ==. It is possible to write objects that compare equal to None, but it is uncommon.

    class A(object):
        def __eq__(self, other):
            return True
    
    print A() == None
    

    Output:

    True
    

    The is operator is also faster, but I don't consider this fact important.

提交回复
热议问题