Python 的整数设计

## Python的整数设计

### 类型定义

[intobject.h/.c]文件中，我们可以比较清晰的看出PyIntObject的定义结构：

typedef struct {
long ob_ival;
} PyIntObject;

PyTypeObject PyInt_Type = {
"int",
sizeof(PyIntObject),
0,
(destructor)int_dealloc,                    /* tp_dealloc */
(printfunc)int_print,                       /* tp_print */
0,                                          /* tp_getattr */
0,                                          /* tp_setattr */
(cmpfunc)int_compare,                       /* tp_compare */
(reprfunc)int_to_decimal_string,            /* tp_repr */
&int_as_number,                             /* tp_as_number */
0,                                          /* tp_as_sequence */
0,                                          /* tp_as_mapping */
(hashfunc)int_hash,

... 省略篇幅
}

static int
int_compare(PyIntObject *v, PyIntObject *w)
{
register long i = v->ob_ival;
register long j = w->ob_ival;
return (i < j) ? -1 : (i > j) ? 1 : 0;
}

### 方法簇

mov x1, 1
add x0, x1

static PyNumberMethods int_as_number = {
(binaryfunc)int_sub,        /*nb_subtract*/
(binaryfunc)int_mul,        /*nb_multiply*/
(binaryfunc)int_classic_div, /*nb_divide*/
(binaryfunc)int_mod,        /*nb_remainder*/
(binaryfunc)int_divmod,     /*nb_divmod*/
(ternaryfunc)int_pow,       /*nb_power*/
(unaryfunc)int_neg,         /*nb_negative*/
(unaryfunc)int_int,         /*nb_positive*/
(unaryfunc)int_abs,         /*nb_absolute*/
(inquiry)int_nonzero,       /*nb_nonzero*/
(unaryfunc)int_invert,      /*nb_invert*/
(binaryfunc)int_lshift,     /*nb_lshift*/
(binaryfunc)int_rshift,     /*nb_rshift*/
(binaryfunc)int_and,        /*nb_and*/
(binaryfunc)int_xor,        /*nb_xor*/
(binaryfunc)int_or,         /*nb_or*/
int_coerce,                 /*nb_coerce*/
(unaryfunc)int_int,         /*nb_int*/
(unaryfunc)int_long,        /*nb_long*/
(unaryfunc)int_float,       /*nb_float*/
(unaryfunc)int_oct,         /*nb_oct*/
(unaryfunc)int_hex,         /*nb_hex*/
0,                          /*nb_inplace_subtract*/