读书人

莫不是是 python 的bug,判断 is 竟然不

发布时间: 2012-12-30 10:43:15 作者: rapoo

难道是 python 的bug,判断 is 竟然不一致
难道是 python 的bug,判断 is 竟然不一致
用代码说话:


>>> a=256
>>> b=256
>>> a is b
True
>>> a=257
>>> b=257
>>> a is b
False
>>>

[解决办法]
判断是不是同一个对象,这个跟 python 对象缓存有关
从结果判断:前面的是同一个对象,后面的是两个对象
[解决办法]
You can easily confuse yourself if you ever talk about applying 'is' to
(for example) integers. Python may re-use certain small integers when
you might not expect it to; this is done in the interests of efficiency.

http://bytes.com/topic/python/answers/523686-what-keyword
[解决办法]
对整数建议别使用is
[解决办法]
is :object identity
is not :negated object identity

[解决办法]
"bug"详见
http://topic.csdn.net/u/20100901/10/c1437de2-fd92-4e50-91cf-3f86431b49a5.html
[解决办法]
python会缓存小整数对象
[解决办法]
缓存的是明确指定的数,如果是变量就没问题的
测试代码
>>> a = 255
>>> b = 255
>>> a is b
True
>>> a = 257
>>> b = 257
>>> a is b
False
>>>for i in range(280):
a,b = i,i
print i, a is b

读书人网 >perl python

热点推荐