Python 是 vs == [英] Python is vs ==

查看:38
本文介绍了Python 是 vs ==的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

<块引用>

可能的重复:
Python 中的字符串比较:is vs ==
什么时候== 运算符不等同于 is 运算符?(Python)

我对 Python 还是很陌生.我听到有人说使用 is,而不是 == 因为这不是 C".但是我有一些代码 x is 5 并且没有按预期工作.

那么,遵循正确的 Python/PEP 风格,什么时候使用 is,什么时候使用 == ?

解决方案

你应该使用 == 来比较两个值.您应该使用 is 来查看两个名称是否绑定到同一个对象.

你几乎不应该使用 x is 5 因为根据实现的不同,可能会保留小整数.这可能会导致令人惊讶的结果:

<预><代码>>>>x = 256>>>x 是 256真的>>>x = 257>>>x 是 257错误的

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 == ?

解决方案

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屋!

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