The int type in python offers two attributes named numerator and real that have the same content as __int__().
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
However I cannot find this hidden property dir dir or either 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 the furthest I can go by myself.
Where the actual value of an integer is stored inside an integer instance?
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.
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.
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)
EDIT: 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__()
You could also use super to explicitly access the int object this way.
(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.)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With