核心語言

Generated Fri 19 Jun 2026 22:08:45 UTC

類別

使用者自訂類別未實作特殊方法 __del__

範例程式碼::

import gc


class Foo:
    def __del__(self):
        print("__del__")


f = Foo()
del f

gc.collect()

CPython output:

MicroPython output:

__del__

__init_subclass__ isn't automatically called.

Cause: MicroPython does not currently implement PEP 487.

Workaround: Manually call __init_subclass__ after class creation if needed. e.g.:

class A(Base):
    pass
A.__init_subclass__()

範例程式碼::

class Base:
    @classmethod
    def __init_subclass__(cls):
        print(f"Base.__init_subclass__({cls.__name__})")


class A(Base):
    pass

CPython output:

MicroPython output:

Base.__init_subclass__(A)

__init_subclass__ isn't an implicit classmethod.

Cause: MicroPython does not currently implement PEP 487. __init_subclass__ is not currently in the list of special-cased class/static methods.

Workaround: Decorate declarations of __init_subclass__ with @classmethod.

範例程式碼::

def regularize_spelling(text, prefix="bound_"):
    # for regularizing across the CPython "method" vs MicroPython "bound_method" spelling for the type of a bound classmethod
    if text.startswith(prefix):
        return text[len(prefix) :]
    return text


class A:
    def __init_subclass__(cls):
        pass

    @classmethod
    def manual_decorated(cls):
        pass


a = type(A.__init_subclass__).__name__
b = type(A.manual_decorated).__name__

print(regularize_spelling(a))
print(regularize_spelling(b))
if a != b:
    print("FAIL")

CPython output:

MicroPython output:

method
method
function
method
FAIL

MicroPython doesn't support parameterized __init_subclass__ class customization.

Cause: MicroPython does not currently implement PEP 487. The MicroPython syntax tree does not include a kwargs node after the class inheritance list.

Workaround: Use class variables or another mechanism to specify base-class customizations.

範例程式碼::

class Base:
    @classmethod
    def __init_subclass__(cls, arg=None, **kwargs):
        cls.init_subclass_was_called = True
        print(f"Base.__init_subclass__({cls.__name__}, {arg=!r}, {kwargs=!r})")


class A(Base, arg="arg"):
    pass


# Regularize across MicroPython not automatically calling __init_subclass__ either.
if not getattr(A, "init_subclass_was_called", False):
    A.__init_subclass__()

CPython output:

MicroPython output:

Base.__init_subclass__(A, arg='arg', kwargs={})
Traceback (most recent call last):
  File "<stdin>", line 16, in <module>
TypeError: function doesn't take keyword arguments

__init_subclass__ can't be defined a cooperatively-recursive way.

Cause: MicroPython does not currently implement PEP 487. The base object type does not have an __init_subclass__ implementation.

Workaround: Omit the recursive __init_subclass__ call unless it's known that the grandparent also defines it.

範例程式碼::

class Base:
    @classmethod
    def __init_subclass__(cls, **kwargs):
        cls.init_subclass_was_called = True
        super().__init_subclass__(**kwargs)


class A(Base):
    pass


# Regularize across MicroPython not automatically calling __init_subclass__ either.
if not getattr(A, "init_subclass_was_called", False):
    A.__init_subclass__()

CPython output:

MicroPython output:

Traceback (most recent call last):
  File "<stdin>", line 22, in <module>
  File "<stdin>", line 13, in __init_subclass__
AttributeError: 'super' object has no attribute '__init_subclass__'

方法解析順序(MRO)與 CPython 不相容

原因: 採用深度優先且非完整的方法解析順序。

因應方式: 避免使用具有多重繼承與複雜方法覆寫的複雜類別階層。請記住,許多程式語言根本不支援多重繼承。

範例程式碼::

class Foo:
    def __str__(self):
        return "Foo"


class C(tuple, Foo):
    pass


t = C((1, 2, 3))
print(t)

CPython output:

MicroPython output:

Foo
(1, 2, 3)

未實作私有類別成員的名稱改編

原因: MicroPython 編譯器未實作私有類別成員的名稱改編。

因應方式: 手動為私有類別成員名稱加上唯一前綴,以避免使用或與全域名稱衝突。

範例程式碼::

def __print_string(string):
    print(string)


class Foo:
    def __init__(self, string):
        self.string = string

    def do_print(self):
        __print_string(self.string)


example_string = "Example String to print."

class_item = Foo(example_string)
print(class_item.string)

class_item.do_print()

CPython output:

MicroPython output:

Example String to print.
Traceback (most recent call last):
  File "<stdin>", line 26, in <module>
  File "<stdin>", line 18, in do_print
NameError: name '_Foo__print_string' is not defined. Did you mean: '__print_string'?
Example String to print.
Example String to print.

繼承原生型別時,在 __init__(self, ...) 中於 super().__init__() 之前呼叫方法會引發 AttributeError(若未啟用 MICROPY_BUILTIN_METHOD_CHECK_SELF_ARG 則可能導致記憶體存取錯誤)。

原因: MicroPython 的原生型別沒有分離的 __new____init__ 方法。

因應方式: 先呼叫 super().__init__()

範例程式碼::

class L1(list):
    def __init__(self, a):
        self.append(a)


try:
    L1(1)
    print("OK")
except AttributeError:
    print("AttributeError")


class L2(list):
    def __init__(self, a):
        super().__init__()
        self.append(a)


try:
    L2(1)
    print("OK")
except AttributeError:
    print("AttributeError")

CPython output:

MicroPython output:

OK
OK
AttributeError
OK

從多個類別繼承時,super() 只會呼叫一個類別

原因: 請參閱 方法解析順序(MRO)與 CPython 不相容

因應方式: 請參閱 方法解析順序(MRO)與 CPython 不相容

範例程式碼::

class A:
    def __init__(self):
        print("A.__init__")


class B(A):
    def __init__(self):
        print("B.__init__")
        super().__init__()


class C(A):
    def __init__(self):
        print("C.__init__")
        super().__init__()


class D(B, C):
    def __init__(self):
        print("D.__init__")
        super().__init__()


D()

CPython output:

MicroPython output:

D.__init__
B.__init__
C.__init__
A.__init__
D.__init__
B.__init__
A.__init__

在子類別中呼叫 super() 的 getter 屬性將回傳 property 物件,而非其值

範例程式碼::

class A:
    @property
    def p(self):
        return {"a": 10}


class AA(A):
    @property
    def p(self):
        return super().p


a = AA()
print(a.p)

CPython output:

MicroPython output:

{'a': 10}
<property>

Exceptions

Throwing a derived exception class instance in its __init__ without first calling super().__init__ is a TypeError

Cause: In MicroPython, an object is incompletely constructed if it does not call its superclass init function or return normally from its __init__. This prevents its usage in some circumstances.

Workaround: Call the superclass __init__ method before raising the exception.

範例程式碼::

class C(Exception):
    def __init__(self):
        raise self


class C1(Exception):
    def __init__(self):
        super().__init__()
        raise self


try:
    C()
except Exception as e:
    print(type(e).__name__)

try:
    C1()
except Exception as e:
    print(type(e).__name__)

CPython output:

MicroPython output:

C
C1
TypeError
C1

函式

方法的錯誤訊息可能顯示非預期的引數數量

原因: MicroPython 將 "self" 計入引數數量。

因應方式: 解讀錯誤訊息時請牢記上述資訊。

範例程式碼::

try:
    [].append()
except Exception as e:
    print(e)

CPython output:

MicroPython output:

list.append() takes exactly one argument (0 given)
function takes 2 positional arguments but 1 were given

函式物件不具有 __module__ 屬性

原因: MicroPython 針對縮減程式碼大小與 RAM 使用量進行了最佳化。

因應方式: 對非內建模組請使用 sys.modules[function.__globals__['__name__']]

範例程式碼::

def f():
    pass


print(f.__module__)

CPython output:

MicroPython output:

__main__
Traceback (most recent call last):
  File "<stdin>", line 13, in <module>
AttributeError: 'function' object has no attribute '__module__'

不支援函式的使用者自訂屬性

原因: MicroPython 針對記憶體使用量進行了高度最佳化。

因應方式: 改用外部字典,例如 FUNC_X[f] = 0

範例程式碼::

def f():
    pass


f.x = 0
print(f.x)

CPython output:

MicroPython output:

0
Traceback (most recent call last):
  File "<stdin>", line 13, in <module>
AttributeError: 'function' object has no attribute 'x'

產生器

未執行完畢的產生器中不會呼叫情境管理器的 __exit__()

範例程式碼::

class foo(object):
    def __enter__(self):
        print("Enter")

    def __exit__(self, *args):
        print("Exit")


def bar(x):
    with foo():
        while True:
            x += 1
            yield x


def func():
    g = bar(0)
    for _ in range(3):
        print(next(g))


func()

CPython output:

MicroPython output:

Enter
1
2
3
Exit
Enter
1
2
3

執行期

區域變數不包含在 locals() 的結果中

原因: MicroPython 不維護符號式區域環境,而是最佳化為插槽陣列,因此無法透過名稱存取區域變數。

範例程式碼::

def test():
    val = 2
    print(locals())


test()

CPython output:

MicroPython output:

{'val': 2}
{'test': <function test at 0x7f5d74c05260>, '__name__': '__main__', '__file__': '<stdin>'}

在 eval() 函式中執行的程式碼無法存取區域變數

原因: MicroPython 不維護符號式區域環境,而是最佳化為插槽陣列,因此無法透過名稱存取區域變數。實際上,MicroPython 中的 eval(expr) 等同於 eval(expr, globals(), globals())

範例程式碼::

val = 1


def test():
    val = 2
    print(val)
    eval("print(val)")


test()

CPython output:

MicroPython output:

2
2
2
1

f-strings

若相鄰字串字面值包含大括號,f-string 不支援與其串接

原因: MicroPython 針對程式碼空間進行了最佳化。

因應方式: 當兩者並非都是 f-string 時,請在字串字面值之間使用 + 運算子。

範例程式碼::

x, y = 1, 2
print("aa" f"{x}")  # works
print(f"{x}" "ab")  # works
print("a{}a" f"{x}")  # fails
print(f"{x}" "a{}b")  # fails

CPython output:

MicroPython output:

aa1
1ab
a{}a1
1a{}b
aa1
1ab
Traceback (most recent call last):
  File "<stdin>", line 12, in <module>
IndexError: tuple index out of range

f-string 不支援需要解析不平衡巢狀大括號與方括號的運算式

原因: MicroPython 針對程式碼空間進行了最佳化。

因應方式: 在 f-string 內的運算式中始終使用成對的大括號與方括號。

範例程式碼::

print(f"{'hello { world'}")
print(f"{'hello ] world'}")

CPython output:

MicroPython output:

hello { world
hello ] world
Traceback (most recent call last):
  File "<stdin>", line 9
SyntaxError: invalid syntax

f-string 不支援 !a 轉換

原因: MicroPython 未實作 ascii()。

因應方式:

範例程式碼::

f"{'unicode text'!a}"

CPython output:

MicroPython output:

Traceback (most recent call last):
  File "<stdin>", line 8
SyntaxError: invalid syntax

import

MicroPython 中套件的 __path__ 屬性型別不同(單一字串而非字串串列)

原因: MicroPython 不支援跨檔案系統分散的命名空間套件。此外,MicroPython 的匯入系統針對最小記憶體使用量進行了高度最佳化。

因應方式: 匯入處理的細節本質上依賴於實作。在可攜式應用程式中請勿依賴此類細節。

範例程式碼::

import modules

print(modules.__path__)

CPython output:

MicroPython output:

['/home/runner/work/openmv-doc/openmv-doc/micropython/tests/cpydiff/modules']
../tests/cpydiff/modules

MicroPython 不支援跨檔案系統分散的命名空間套件。

原因: MicroPython 的匯入系統針對簡潔性、最小記憶體使用量及最小檔案系統搜尋開銷進行了高度最佳化。

因應方式: 請勿將屬於相同命名空間套件的模組安裝在不同目錄中。對於 MicroPython,建議模組搜尋路徑最多包含 3 個層次:目前應用程式、每位使用者(可寫入)、全系統(不可寫入)。

範例程式碼::

import sys

sys.path.append(sys.path[1] + "/modules")
sys.path.append(sys.path[1] + "/modules2")

import subpkg.foo
import subpkg.bar

print("Two modules of a split namespace package imported")

CPython output:

MicroPython output:

Two modules of a split namespace package imported
Traceback (most recent call last):
  File "<stdin>", line 14, in <module>
ImportError: no module named 'subpkg.bar'