Python 是 vs ==
可能的重复:
Python 中的字符串比较:is 与 ==
什么时候== 运算符不等于
is
运算符? (Python)
我对 Python 还很陌生。我听到有人说使用 is
,而不是 ==
因为“这不是 C”。但我有一些代码 x is 5
并且它没有按预期工作。
那么,遵循正确的 Python/PEP 风格,什么时候使用 is
以及什么时候使用 ==
?
Possible Duplicate:
String comparison in Python: is vs. ==
When is the==
operator not equivalent to theis
operator? (Python)
I'm pretty new to Python still. I heard someone say use is
, not ==
because "this isn't C". But I had some code x is 5
and it was not working as expected.
So, following proper Python/PEP style, when is the time to use is
and when is the time to use ==
?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
您应该使用
==
来比较两个值。您应该使用is
来查看两个名称是否绑定到同一个对象。您几乎不应该使用
x is 5
,因为根据实现的不同,小整数可能会被保留。这可能会导致令人惊讶的结果:You should use
==
to compare two values. You should useis
to see if two names are bound to the same object.You should almost never use
x is 5
because depending on the implementation small integers might be interned. This can lead to surprising results:这两个运算符具有不同的含义。
is
测试对象身份。两个操作数是否引用同一个对象?==
测试值的相等性。两个操作数的值是否相同?当比较
x
和5
时,您总是对值感兴趣,而不是保存该值的对象。The two operators have different meaning.
is
tests object identity. Do the two operands refer to the same object?==
tests equality of value. Do the two operands have the same value?When it comes to comparing
x
and5
you invariably are interested in the value rather than the object holding the value.