Where is the int value for an int instance stored in Python?

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

Since all these 3 values ​​return the same internal attribute, I think real is a property like this:

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

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

So, I looked at the source code and found this:

 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 */ }; 

And this:

 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 is the further that I can do myself.

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

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

+3
source share
1 answer

The actual integer value is in ob_ival . Essentially, int_int simply takes an integer value from one int object and transfers it to another object.

Not sure why you cannot see the properties. If I run this, they will appear for me in versions 2.7 and 3.4:

 x = 8 dir(x) 

EDIT: It's too hard to explain in a comment, so adding an answer.

You can easily subclass it as follows:

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

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

(You understand that __getitem__ is for use with key objects [dict-like, say] and therefore usually gets a second argument defining a key, right? Both int and float do not have a key).

+2
source

Source: https://habr.com/ru/post/1271216/


All Articles