问题
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