python - 为什么 int(maxint) 给出的是 long,而 int(int(maxint)) 给出的是 int?这是 NumPy 错误吗?

标签 python python-2.7 numpy int long-integer

非常不言自明(我在 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 中没有单独的 intlong类型。

该行为的发生是由于 numpy 中的一个差一错误。 int(x)用一个参数转换 x调用电话号码 PyNumber_Int(x) . PyNumber_Int然后专门取path for int subclasses , 作为 int64numpy.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通过条件,它们反而被转换成 PyLongline 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/

相关文章:

python - 为什么描述符 __get__ 可以访问对象的类型但 __set__ 不能?

python - 属性错误: 'module' object has no attribute 'SMAC_optimizer'

python - Google 表格 "repeatCell"从现有单元格中剥离格式

python - 解析 XML 数据文件结果为 json 或 dict

python - 无法用 lambda 覆盖 __contains__

python - 使用 python 获取屏幕上文本的 x , y 坐标

python - 如何绘制经验 cdf (ecdf)

python - 对 numpy 数组中的每一行应用函数?

python - 平滑连接输入的正弦波