最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

不恰当使用“不是"比较导致的奇怪 Python 行为?

网站源码admin355浏览0评论
本文介绍了不恰当使用“不是"比较导致的奇怪 Python 行为?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

限时送ChatGPT账号..

我(错误地?)在比较中使用了不是"并发现了这种奇怪的行为:

<预><代码>>>>一 = 256>>>b = int('256')>>>c = 300>>>d = int('300')>>>>>>a 不是 b错误的>>>c 不是 d真的

显然我应该使用:

<预><代码>>>>一个!= b错误的>>>c != d错误的

但是由于小价值的测试用例,它工作了很长时间,直到我碰巧使用 495 的数字.

如果这是无效的语法,那为什么?难道我不应该至少得到警告吗?

解决方案

"is" 不是检查值是否相等,而是检查两个变量是否指向同一对象实例.

ints 和 strings 对此会造成混淆,因为 is== 可能恰好给出由于语言内部的工作方式,结果相同.

I (incorrectly?) used 'is not' in a comparison and found this curious behavior:

>>> a = 256
>>> b = int('256')
>>> c = 300
>>> d = int('300')
>>>
>>> a is not b
False
>>> c is not d
True

Obviously I should have used:

>>> a != b
False
>>> c != d
False

But it worked for a long time due to small-valued test-cases until I happened to use a number of 495.

If this is invalid syntax, then why? And shouldn't I at least get a warning?

解决方案

"is" is not a check of equality of value, but a check that two variables point to the same instance of an object.

ints and strings are confusing for this as is and == can happen to give the same result due to how the internals of the language work.

这篇关于不恰当使用“不是"比较导致的奇怪 Python 行为?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

发布评论

评论列表(0)

  1. 暂无评论