问题描述
我(错误地?)在比较中使用了不是"并发现了这种奇怪的行为:
>>>一 = 256>>>b = int('256')>>>c = 300>>>d = int('300')>>>>>>a 不是 b错误的>>>c 不是 d真的显然我应该使用:
>>>一个!= b错误的>>>c != d错误的但是由于小价值的测试用例,它工作了很长时间,直到我碰巧使用 495 的数字.
如果这是无效的语法,那为什么?难道我不应该至少得到警告吗?
"is" 不是检查值是否相等,而是检查两个变量是否指向同一对象实例.
int
s 和 string
s 对此会造成混淆,因为 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 touse 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.
int
s and string
s are confusing for this as is
and ==
can happen to give the same result due to how the internals of the language work.
这篇关于不恰当使用“不是"比较导致的奇怪 Python 行为?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!