哪里存储了Python中int实例的int值? [英] Where is stored the int value of a int instance in Python?

查看:111
本文介绍了哪里存储了Python中int实例的int值?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

python中的 int 类型提供了两个名为 numerator real __ int __()具有相同的内容。

The int type in python offers two attributes named numerator and real that have the same content as __int__().

由于所有这3个值都返回相同的内部属性,我猜 real 是一个属性,如:

As all of these 3 values returns the same internal attribute, I guess real is a property like:

@property
def real(self):
   return self.__int

但是我找不到这个隐藏的属性目录 dir 或者 a = int(); IPython中的a._int __< tab>

However I cannot find this hidden property dir dir or either a = int(); a._int__<tab> in IPython.

所以我看了源代码并发现:

static PyGetSetDef int_getset[] = {
    {"real",
     (getter)int_int, (setter)NULL,
     "the real part of a complex number",
     NULL},
    {"imag",
     (getter)int_get0, (setter)NULL,
     "the imaginary part of a complex number",
     NULL},
    {"numerator",
     (getter)int_int, (setter)NULL,
     "the numerator of a rational number in lowest terms",
     NULL},
    {"denominator",
     (getter)int_get1, (setter)NULL,
     "the denominator of a rational number in lowest terms",
     NULL},
    {NULL}  /* Sentinel */
};

这个:

static PyObject *
int_int(PyIntObject *v)
{
    if (PyInt_CheckExact(v))
        Py_INCREF(v);
    else
        v = (PyIntObject *)PyInt_FromLong(v->ob_ival);
    return (PyObject *)v;
}

但这是我自己可以去的最远的地方。

But this the furthest I can go by myself.

整数的实际值是否存储在整数实例中?

Where the actual value of an integer is stored inside an integer instance?

这个问题的主要原因是我想用 MyFloat 扩展 float 类型,其中我想引用实例的值。

The main reason for this question is that I want to extend the float type with a MyFloat where I would like to refer to the value of the instance.

推荐答案

实际的整数值在 ob_ival 中。实质上, int_int 只是从一个 int 对象获取整数值并将其包装在另一个对象中。

The actual integer value is in ob_ival. In essence, int_int is simply taking the integer value from one int object and wrapping it in another object.

不确定为什么你看不到这些属性。如果我运行它,它们会出现在2.7和3.4版本中:

Not sure why you can't see the properties. If I run this, they show up for me, in both 2.7 and 3.4 versions:

x = 8
dir(x)

编辑:
在评论中难以解释,所以加入回答。

Too hard to explain in a comment, so adding to the answer.

你可以像这样轻松地对它进行子类化:

You could easily subclass it like this:

class foo(int):
    def __getitem__(self):
        return self + 1

foo(8).__getitem__()

您还可以使用 super 显式访问 int 以这种方式反对。

You could also use super to explicitly access the int object this way.

(您确实意识到 __ getitem __ 用于键控对象[类似于dict],因此通常获取指定键的第二个参数,对吗? int float 未键入。)

(You do realize that __getitem__ is for use with keyed objects [dict-like, say] and hence normally gets a second argument specifying the key, right? And int and float are not keyed.)

这篇关于哪里存储了Python中int实例的int值?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆