Python is vs == [duplicate]

走远了吗. 提交于 2021-02-07 23:01:14

问题


Possible Duplicate:
String comparison in Python: is vs. ==
When is the == operator not equivalent to the is 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 == ?


回答1:


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



回答2:


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 and 5 you invariably are interested in the value rather than the object holding the value.



来源:https://stackoverflow.com/questions/7718790/python-is-vs

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!