在Python中为None [英] identity versus equality for None in Python

查看:393
本文介绍了在Python中为None的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

各种Python指南说使用 x是无而不是 x == None 。这是为什么?平等用于比较值,因此看来是否 x 具有值 None ,表示为 == 而不是。有人可以解释为什么是首选表单,并显示一个示例,其中两个不给出相同的答案?

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 x has the value None, denoted with == and not is. Can someone explain why is is the preferred form and show an example where the two do not give the same answer?

感谢。

推荐答案

人们使用是因为使用 == 没有优势。可以编写比较等于 None 的对象,但不常见。

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

输出:

True

不要认为这个事实很重要。

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

这篇关于在Python中为None的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆