当一个数字的值超出整数范围时,python将它提升为long.但是当值回到整数范围时,为什么不将它降级为int?
>>> i=2147483647
>>> type(i)
>>> i = i + 1
>>> type(i)
>>> i = i - 10
>>> type(i)
>>> i
2147483638L
>>>
解决方法:
从python source(在文件Objects / longobject.c中):
static PyLongObject *
x_add(PyLongObject *a, PyLongObject *b)
{
Py_ssize_t size_a = ABS(a->ob_size), size_b = ABS(b->ob_size);
PyLongObject *z;
int i;
digit carry = 0;
/* Ensure a is the larger of the two: */
if (size_a < size_b) {
{ PyLongObject *temp = a; a = b; b = temp; }
{ Py_ssize_t size_temp = size_a;
size_a = size_b;
size_b = size_temp; }
}
z = _PyLong_New(size_a+1);
if (z == NULL)
return NULL;
for (i = 0; i < size_b; ++i) {
carry += a->ob_digit[i] + b->ob_digit[i];
z->ob_digit[i] = carry & MASK;
carry >>= SHIFT;
}
for (; i < size_a; ++i) {
carry += a->ob_digit[i];
z->ob_digit[i] = carry & MASK;
carry >>= SHIFT;
}
z->ob_digit[i] = carry;
return long_normalize(z);
}
/* Subtract the absolute values of two integers. */
static PyLongObject *
x_sub(PyLongObject *a, PyLongObject *b)
{
Py_ssize_t size_a = ABS(a->ob_size), size_b = ABS(b->ob_size);
PyLongObject *z;
Py_ssize_t i;
int sign = 1;
digit borrow = 0;
/* Ensure a is the larger of the two: */
if (size_a < size_b) {
sign = -1;
{ PyLongObject *temp = a; a = b; b = temp; }
{ Py_ssize_t size_temp = size_a;
size_a = size_b;
size_b = size_temp; }
}
else if (size_a == size_b) {
/* Find highest digit where a and b differ: */
i = size_a;
while (--i >= 0 && a->ob_digit[i] == b->ob_digit[i])
;
if (i < 0)
return _PyLong_New(0);
if (a->ob_digit[i] < b->ob_digit[i]) {
sign = -1;
{ PyLongObject *temp = a; a = b; b = temp; }
}
size_a = size_b = i+1;
}
z = _PyLong_New(size_a);
if (z == NULL)
return NULL;
for (i = 0; i < size_b; ++i) {
/* The following assumes unsigned arithmetic
works module 2**N for some N>SHIFT. */
borrow = a->ob_digit[i] - b->ob_digit[i] - borrow;
z->ob_digit[i] = borrow & MASK;
borrow >>= SHIFT;
borrow &= 1; /* Keep only one sign bit */
}
for (; i < size_a; ++i) {
borrow = a->ob_digit[i] - borrow;
z->ob_digit[i] = borrow & MASK;
borrow >>= SHIFT;
borrow &= 1; /* Keep only one sign bit */
}
assert(borrow == 0);
if (sign < 0)
z->ob_size = -(z->ob_size);
return long_normalize(z);
}
请注意,两个过程的返回类型都是PyLongObject *.
这表明,long的加法和减法在python中产生更多的long,无论值是否适合整数.
例:
>>> 3L + 4L
7L
here是python的强制规则,具体来说:
For objects x and y, first x.__add__(y) is tried. If this is not
implemented or returns NotImplemented, y.__add__(x) is tried. If this
is also not implemented or returns NotImplemented, a TypeError
exception is raised.
所以做i – 10,我很长,导致另一个长.
标签:python,types