您好, 欢迎来到 !    登录 | 注册 | | 设为首页 | 收藏本站

Python None比较:我应该使用“ is”还是==?

Python None比较:我应该使用“ is”还是==?

摘要: 使用is时要核对对象的身份(如检查,看看是否varNone)。使用==时要检查的平等(例如是var等于3?)。

说明: 你可以在其中my_var == None返回的自定义类True

例如:

class Negator(object):
    def __eq__(self,other):
        return not other

thing = Negator()
print thing == None    #True
print thing is None    #False

is检查对象身份。只有1个对象None,因此在执行操作时my_var is None,你要检查它们是否实际上是同一对象(而不仅仅是等效对象)

换句话说,==是检查等效性(定义在对象之间),而is检查对象身份:

lst = [1,2,3]
lst == lst[:]  # This is True since the lists are "equivalent"
lst is lst[:]  # This is False since they're actually different objects
python 2022/1/1 18:24:17 有520人围观

撰写回答


你尚未登录,登录后可以

和开发者交流问题的细节

关注并接收问题和回答的更新提醒

参与内容的编辑和改进,让解决方法与时俱进

请先登录

推荐问题


联系我
置顶