簡體   English   中英

** 在 Python 中是如何實現的?

[英]How is ** implemented in Python?

我想知道在哪里可以找到顯示運算符 ** 如何在 Python 中實現的源代碼。 有人可以指出我正確的方向嗎?

python 語法定義(使用pgen 從中生成解析器),查找“power”: Gramar/Gramar

python ast,尋找'ast_for_power': Python/ast.c

python eval 循環,查找“BINARY_POWER”: Python/ceval.c

其中調用 PyNumber_Power(在Objects/abstract.c 中實現):

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

本質上,調用pow插槽。 對於 long 對象(3.0 中唯一的默認整數類型),這是在 long_pow 函數Objects/longobject.c 中實現的,對於 int 對象(在 2.x 分支中),它是在 int_pow 函數Object/intobject.c 中實現的

如果您深入研究 long_pow,您會發現在審查參數並進行一些設置后,可以在這里看到求冪的核心:

if (Py_SIZE(b) <= FIVEARY_CUTOFF) {
    /* Left-to-right binary exponentiation (HAC Algorithm 14.79) */
    /* http://www.cacr.math.uwaterloo.ca/hac/about/chap14.pdf    */
    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)
        }
    }
}

它使用在《應用密碼學手冊》第 14.6 章中討論的算法,該描述了用於任意精度算術的有效冪運算算法。

有兩種不同的實現,一種用於 int(3.0 中的 long)對象,另一種用於 float 對象。

float pow 是 Python 源代碼的 Objects/floatobject.c 文件中定義的 float_pow(PyObject *v, PyObject *w, PyObject *z) 函數。 此函數從 C stdlib 的 math.h 調用 pow()

int pow 有自己的實現,是在 Python 源代碼的 Objects/intobject.c (longobject.c for 3.0) 中定義的函數 int_pow(PyIntObject *v, PyIntObject *w, PyIntObject *z)。

我認為 caseysrandomthoughts 在函數定義中詢問星號。

你可以在這個 Python 文檔頁面找到答案: http : //docs.python.org/tutorial/controlflow.html#more-on-defining-functions

當存在形式為 **name 的最終形參時,它會收到一個字典,其中包含除與形參對應的關鍵字參數之外的所有關鍵字參數。

我在 python doc 的其他地方播下了對這些東西的描述,但我不記得了。

這是運營商的權力

python.org doc - 電力運營商

編輯:哦,當,代碼,對。 希望鏈接仍然有幫助。 從我的部分草率閱讀

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM