Python的首选比较运算符 [英] Python's preferred comparison operators

查看:95
本文介绍了Python的首选比较运算符的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

是否优先:

if x is y:
    return True

if x == y
    return True

同样的事情是不是

推荐答案

x是y 不同于 x == y

x是y id(x)== id(y) - 也就是 x y 必须是同一个对象(具有相同的 id s)。

x is y is true if and only if id(x) == id(y) -- that is, x and y have to be one and the same object (with the same ids).

对于所有内置Python对象(如字符串,列表,命令,函数等),如果 x是y ,则 x == y 也为True。但是,这一般不能保证。严格地说,当且仅当 x .__ eq __(y)返回True时, x == y

For all built-in Python objects (like strings, lists, dicts, functions, etc.), if x is y, then x == y is also True. However, this is not guaranteed in general. Strictly speaking, x == y is true if and only if x.__eq__(y) returns True.

可以使用 __ eq __ x c>方法,它总是返回False,例如,这将导致 x == y 返回False,即使 x是y

It is possible to define an object x with a __eq__ method which always returns False, for example, and this would cause x == y to return False, even if x is y.

所以底线是 x是y x == y 是完全不同的测试。

So the bottom line is, x is y and x == y are completely different tests.

请考虑这个例子:

In [1]: 0 is False
Out[1]: False

In [2]: 0 == False
Out[2]: True

PS。而不是

if x is y:
    return True
else:
    return False

它更像Pythonic写

it is more Pythonic to write

return x is y

同样,

if x == y:
    return True
else:
    return False

可以替换为

return x == y

这篇关于Python的首选比较运算符的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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