Python 是 vs == [英] Python is vs ==
问题描述
可能的重复:
Python 中的字符串比较:is vs ==
什么时候==
运算符不等同于 is
运算符?(Python)
我对 Python 还是很陌生.我听到有人说使用 is
,而不是 ==
因为这不是 C".但是我有一些代码 x is 5
并且没有按预期工作.
那么,遵循正确的 Python/PEP 风格,什么时候使用 is
,什么时候使用 ==
?
你应该使用 ==
来比较两个值.您应该使用 is
来查看两个名称是否绑定到同一个对象.
你几乎不应该使用 x is 5
因为根据实现的不同,可能会保留小整数.这可能会导致令人惊讶的结果:
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 ==
?
You should use ==
to compare two values. You should use is
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:
>>> x = 256
>>> x is 256
True
>>> x = 257
>>> x is 257
False
这篇关于Python 是 vs ==的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!