非常不言自明(我在 Windows 上):
>>> import sys, numpy
>>> a = numpy.int_(sys.maxint)
>>> int(a).__class__
<type 'long'>
>>> int(int(a)).__class__
<type 'int'>
为什么调用 int
一次得到一个 long
,而调用它两次得到一个 int
?
这是错误还是功能?
最佳答案
这个问题特定于 Numpy 和 Python 2。在 Python 3 中没有单独的 int
和 long
类型。
该行为的发生是由于 numpy 中的一个差一错误。 int(x)
用一个参数转换 x
调用电话号码 PyNumber_Int(x)
. PyNumber_Int
然后专门取path for int
subclasses , 作为 int64
由 numpy.int_
返回是 int
的子类:
m = o->ob_type->tp_as_number;
if (m && m->nb_int) { /* This should include subclasses of int */
/* Classic classes always take this branch. */
PyObject *res = m->nb_int(o);
if (res && (!PyInt_Check(res) && !PyLong_Check(res))) {
PyErr_Format(PyExc_TypeError,
"__int__ returned non-int (type %.200s)",
res->ob_type->tp_name);
Py_DECREF(res);
return NULL;
}
return res;
}
现在,此代码调用 a->ob_type->tp_as_number->nb_int
,在 numpy/core/src/umath/scalarmath.c.src 中实现.这是为不同类型参数化的代码的位置;这个是<typename>_int
用于填充 nb_int
的方法方法插槽。它有以下关闭一个 if
那里:
if(LONG_MIN < x && x < LONG_MAX)
return PyInt_FromLong(x);
两个运算符都应该是<=
反而。与 <
那里,既不LONG_MIN
也不LONG_MAX
通过条件,它们反而被转换成 PyLong
在 line 1432 :
return @func@(x);
与 @func@
被 PyLong_FromLongLong
取代在 int_
的情况下.因此,long(sys.maxint)
被退回。
现在,作为 sys.maxint
仍由 int
表示, int(long(sys.maxint))
返回 int
;同样int(sys.maxint + 1)
返回 long
.
关于python - 为什么 int(maxint) 给出的是 long,而 int(int(maxint)) 给出的是 int?这是 NumPy 错误吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44155560/