Python 程式碼物件
程式碼物件是 CPython 實現的低階細節。每個程式碼物件都表示一段尚未繫結到函式中的可執行程式碼。雖然程式碼物件表示一段可執行程式碼,但它們本身並不能直接呼叫。如需執行程式碼物件,必須使用 exec 關鍵字。
在下面的示例中,我們將看到如何為給定的程式碼塊建立程式碼物件,以及與該程式碼物件關聯的各種屬性。
示例
code_str = """ print("Hello Code Objects") """ # Create the code object code_obj = compile(code_str, '<string>', 'exec') # get the code object print(code_obj) #Attributes of code object print(dir(code_obj)) # The filename print(code_obj.co_filename) # The first chunk of raw bytecode print(code_obj.co_code) #The variable Names print(code_obj.co_varnames)
輸出
執行以上程式碼,得到以下結果 −
<code object <module> at 0x000001D80557EF50, file "<string>", line 2> ['__class__', '__delattr__', '__dir__', '__doc__', ……., '__subclasshook__', 'co_argcount', 'co_cellvars', 'co_code', 'co_consts', 'co_filename', 'co_firstlineno', …..,posonlyargcount', 'co_stacksize', 'co_varnames', 'replace'] <string> b'e\x00d\x00\x83\x01\x01\x00d\x01S\x00' ()
廣告