什麼是 python 中的編譯和連結過程?


編譯 − Python 中的原始碼儲存為 .py 檔案,然後編譯成位元組程式碼格式,位元組程式碼再轉換為機器程式碼。編譯後,程式碼儲存在 .pyc 檔案中,並且在更新原始碼時重新生成。此過程稱為編譯。

連結 − 連結是將所有函式連結到其定義的最後階段,因為連結器知道所有這些函式在哪裡實現。此過程稱為連結。

image compilation.jpg-----

注意 − Python 程式既被編譯又會被解釋,但編譯部分對程式設計師是隱藏的。因此,我們通常說 Python 出於相同的原因是一種解釋語言。

我們來看看一個例子。對於我們的示例,我們將使用 Python 中的 dis 模組。

安裝並匯入 dis 模組

要安裝 dis 模組,請使用 pip −

pip install dis

要匯入 dis 模組 −

import dis

示例

現在讓我們看一個示例

import dis # Function to return the sum of recursive numbers def recursive_sum(n): if n <= 1: return n else: return n + recursive_sum(n-1) # change this value for a different result number = 16 if number < 0: print("The sum = ",recursive_sum(number)) # By using dis module, the bytecode is loaded into machine code, and a piece of code that reads each instruction in the bytecode and executes whatever operation is indicated. dis.dis(recursive_sum)

輸出

  5           0 LOAD_FAST                0 (n)
              2 LOAD_CONST               1 (1)
              4 COMPARE_OP               1 (<=)
              6 POP_JUMP_IF_FALSE       12

  6           8 LOAD_FAST                0 (n)
             10 RETURN_VALUE

  8     >>   12 LOAD_FAST                0 (n)
             14 LOAD_GLOBAL              0 (recursive_sum)
             16 LOAD_FAST                0 (n)
             18 LOAD_CONST               1 (1)
             20 BINARY_SUBTRACT
             22 CALL_FUNCTION            1
             24 BINARY_ADD
             26 RETURN_VALUE
             28 LOAD_CONST               0 (None)
             30 RETURN_VALUE

更新於:2022-08-12

6 千 + 檢視

開啟你的 職業

完成課程,獲得證書

開始
廣告
© . All rights reserved.