### 如何在Python中实现**？

#### 4 个答案:

python语法定义（使用pgen从中生成解析器），寻找'power'：Gramar/Gramar

python ast，寻找'ast_for_power'：Python/ast.c

python eval循环，查找'BINARY_POWER'：Python/ceval.c

``````PyObject *
PyNumber_Power(PyObject *v, PyObject *w, PyObject *z)
{
return ternary_op(v, w, z, NB_SLOT(nb_power), "** or pow()");
}
``````

``````if (Py_SIZE(b) <= FIVEARY_CUTOFF) {
/* Left-to-right binary exponentiation (HAC Algorithm 14.79) */
for (i = Py_SIZE(b) - 1; i >= 0; --i) {
digit bi = b->ob_digit[i];

for (j = 1 << (PyLong_SHIFT-1); j != 0; j >>= 1) {
MULT(z, z, z)
if (bi & j)
MULT(z, a, z)
}
}
}
else {
/* Left-to-right 5-ary exponentiation (HAC Algorithm 14.82) */
Py_INCREF(z);   /* still holds 1L */
table[0] = z;
for (i = 1; i < 32; ++i)
MULT(table[i-1], a, table[i])

for (i = Py_SIZE(b) - 1; i >= 0; --i) {
const digit bi = b->ob_digit[i];

for (j = PyLong_SHIFT - 5; j >= 0; j -= 5) {
const int index = (bi >> j) & 0x1f;
for (k = 0; k < 5; ++k)
MULT(z, z, z)
if (index)
MULT(z, table[index], z)
}
}
}
``````

float pow是Python源代码的Objects / floatobject.c文件中定义的float_pow（PyObject * v，PyObject * w，PyObject * z）函数。这个函数从C stdlib的math.h

int pow有自己的实现，是Python源代码的Objects / intobject.c（longobject.c for 3.0）中定义的函数int_pow（PyIntObject * v，PyIntObject * w，PyIntObject * z）。 p>