原创作者: simohayha   阅读:3811次   评论:0条   更新时间:2011-06-01    
请看这段程序
a = 0
b = 0
while a is b:
    a += 1
    b += 1
print id(a), a
print id(b), b

猜猜结果,呵呵结果是
13013836 257
13013812 257
原因在这里:

引用
This is really hardcoded limit in the current CPython implementation
The interpreter preallocates numbers from 0 to 256.


大家可以看下intobject.c的有关这部分的源码:
#ifndef NSMALLPOSINTS
#define NSMALLPOSINTS		257
#endif
#ifndef NSMALLNEGINTS
#define NSMALLNEGINTS		5
#endif
#if NSMALLNEGINTS + NSMALLPOSINTS > 0
/* References to small integers are saved in this array so that they
   can be shared.
   The integers that are saved are those in the range
   -NSMALLNEGINTS (inclusive) to NSMALLPOSINTS (not inclusive).
*/
static PyIntObject *small_ints[NSMALLNEGINTS + NSMALLPOSINTS];
#endif
#ifdef COUNT_ALLOCS
int quick_int_allocs, quick_neg_int_allocs;
#endif

呵呵,一目了然吧.
这边给我们的教训就是判断数字相等不要用 is操作符,哈哈.
评论 共 0 条 请登录后发表评论

发表评论

您还没有登录,请您登录后再发表评论

文章信息

Global site tag (gtag.js) - Google Analytics