types --- 內建型別的名稱

本模組為標準 Python 直譯器使用、但未以內建名稱對外公開的若干物件型別(例如函式或產生器的型別)定義名稱,同時提供少量用於動態建構類別的輔助函式。

這是 CPython types 模組子集的 MicroPython 移植版本。有幾個在 MicroPython 中沒有實際意義的型別別名(CodeTypeMappingProxyTypeSimpleNamespaceTracebackTypeFrameTypeGetSetDescriptorTypeMemberDescriptorType)以 None 佔位符的形式公開,讓僅引用它們的程式碼仍可順利匯入,但它們不會透過 isinstance() 與任何真實物件相符。

可用性: 本模組是 micropython-lib 的一部分。它僅在 OpenMV N6 與 OpenMV AE3 上預設包含。在其他 OpenMV Cam 上可以使用 mip 安裝(或凍結進自訂韌體);請參閱 套件管理

型別別名

types.FunctionType: type

使用者定義函式以及由 def 陳述式建立的物件的型別。

types.LambdaType: type

lambda 運算式的型別。與 FunctionType 相同。

types.GeneratorType: type

由產生器函式產生的產生器-迭代器物件的型別。

types.MethodType: type

使用者定義類別實例的繫結方法的型別。

types.BuiltinFunctionType: type

內建函式(例如 len()sys.exit())的型別。

types.BuiltinMethodType: type

內建型別的繫結方法(例如 [].append)的型別。與 BuiltinFunctionType 相同。

types.ModuleType: type

已匯入模組的型別。

types.CodeType: None

CPython code 物件型別的佔位符。在本實作中永遠為 None

types.MappingProxyType: None

CPython 中由 type.__dict__ 傳回的唯讀對映代理型別的佔位符。在本實作中永遠為 None

types.SimpleNamespace: None

CPython types.SimpleNamespace 類別的佔位符。在本實作中永遠為 None

types.TracebackType: None

回溯物件型別的佔位符。在本實作中永遠為 None

types.FrameType: None

影格物件型別的佔位符。在本實作中永遠為 None

types.GetSetDescriptorType: None

由擴充型別定義的屬性描述子型別的佔位符。在本實作中永遠為 None

types.MemberDescriptorType: None

由擴充型別定義的插槽描述子型別的佔位符。在本實作中永遠為 None

函式

types.new_class(name: str, bases: tuple = (), kwds: dict | None = None, exec_body: Callable[[dict], None] | None = None) type

以模擬符合 PEP 3115 規範的 class 陳述式的方式動態建立類別物件。

  • name 是新類別的名稱。

  • bases 是基底類別組成的元組。

  • kwds 是要傳遞給中介類別的關鍵字引數字典。若存在 "metaclass" 鍵,則直接以它選定中介類別。

  • exec_body 是一個選用的可呼叫物件,會以剛準備好的類別命名空間被呼叫;它應以新類別的屬性填入該命名空間。

傳回新建構的類別。

types.prepare_class(name: str, bases: tuple = (), kwds: dict | None = None) tuple[type, dict, dict]

計算適當的中介類別並為新類別準備命名空間。

  • name 是即將建立的類別的名稱。

  • bases 是基底類別組成的元組。

  • kwds 是關鍵字引數字典。若存在 "metaclass" 鍵,則會從傳回的 kwds 中移除並用作中介類別。否則會使用 bases[0] 的中介類別,並回退至 type

傳回一個 3 元組 (metaclass, namespace, kwds),其中 namespace 為在有定義時呼叫 metaclass.__prepare__ 的結果,否則為空字典,而 kwds 為移除任何 "metaclass" 項目後的輸入副本。