ภาษาหลัก¶
Generated Thu 18 Jun 2026 19:58:13 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__'
|
Method Resolution Order (MRO) ไม่สอดคล้องกับ CPython¶
สาเหตุ: การแก้ไขเมธอดแบบ Depth first ที่ไม่ครอบคลุมทั้งหมด
วิธีแก้ไข: หลีกเลี่ยงลำดับชั้นคลาสที่ซับซ้อนที่มีการสืบทอดหลายรายการและการ override เมธอดที่ซับซ้อน โปรดจำไว้ว่าหลายภาษาไม่รองรับการสืบทอดหลายรายการเลย
โค้ดตัวอย่าง:
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)
|
ยังไม่รองรับการแปลงชื่อ Private Class Members (name mangling)¶
สาเหตุ: คอมไพเลอร์ MicroPython ไม่รองรับ name mangling สำหรับ private class members
วิธีแก้ไข: หลีกเลี่ยงการใช้หรือมีการชนกับชื่อ global โดยการเพิ่ม prefix ที่ไม่ซ้ำกันให้กับชื่อ private class member ด้วยตนเอง
โค้ดตัวอย่าง:
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.
|
เมื่อสืบทอดประเภท native การเรียกเมธอดใน __init__(self, ...) ก่อน super().__init__() จะ raise AttributeError (หรือ segfault หาก MICROPY_BUILTIN_METHOD_CHECK_SELF_ARG ไม่ได้เปิดใช้งาน)¶
สาเหตุ: MicroPython ไม่มีเมธอด __new__ และ __init__ แยกกันในประเภท native
วิธีแก้ไข: เรียก 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() จะเรียกเพียงคลาสเดียวเท่านั้น¶
สาเหตุ: ดู Method Resolution Order (MRO) ไม่สอดคล้องกับ CPython
วิธีแก้ไข: ดู Method Resolution Order (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 ในคลาสย่อยจะคืนค่าออบเจ็กต์ 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__']] สำหรับโมดูลที่ไม่ใช่ builtin
โค้ดตัวอย่าง:
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 ได้รับการปรับให้เหมาะสมอย่างมากสำหรับการใช้หน่วยความจำ
วิธีแก้ไข: ใช้ dictionary ภายนอก เช่น 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'
|
Generator¶
Context manager __exit__() ไม่ถูกเรียกใน generator ที่ไม่ทำงานจนเสร็จสิ้น¶
โค้ดตัวอย่าง:
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
|
Runtime¶
ตัวแปรท้องถิ่นไม่ถูกรวมอยู่ในผลลัพธ์ของ locals()¶
สาเหตุ: MicroPython ไม่รักษาสภาพแวดล้อมท้องถิ่นเชิงสัญลักษณ์ แต่ถูกปรับให้เหมาะสมเป็น array ของ slot ดังนั้นตัวแปรท้องถิ่นจึงไม่สามารถเข้าถึงได้โดยใช้ชื่อ
โค้ดตัวอย่าง:
def test():
val = 2
print(locals())
test()
CPython output: |
MicroPython output: |
{'val': 2}
|
{'test': <function test at 0x7f186c605260>, '__name__': '__main__', '__file__': '<stdin>'}
|
โค้ดที่รันใน eval() ไม่สามารถเข้าถึงตัวแปรท้องถิ่นได้¶
สาเหตุ: MicroPython ไม่รักษาสภาพแวดล้อมท้องถิ่นเชิงสัญลักษณ์ แต่ถูกปรับให้เหมาะสมเป็น array ของ slot ดังนั้นตัวแปรท้องถิ่นจึงไม่สามารถเข้าถึงได้โดยใช้ชื่อ โดยพื้นฐานแล้ว eval(expr) ใน MicroPython เทียบเท่ากับ 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-strings ไม่รองรับการเชื่อมต่อกับ literal ที่อยู่ติดกันหากมีวงเล็บปีกกาอยู่ใน literal นั้น¶
สาเหตุ: MicroPython ได้รับการปรับให้เหมาะสมสำหรับพื้นที่โค้ด
วิธีแก้ไข: ใช้ตัวดำเนินการ + ระหว่าง literal strings เมื่อไม่ใช่ f-strings ทั้งคู่
โค้ดตัวอย่าง:
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-strings ไม่รองรับนิพจน์ที่ต้องการการแยกวิเคราะห์เพื่อแก้ไขวงเล็บและวงเล็บปีกกาที่ไม่สมดุล¶
สาเหตุ: MicroPython ได้รับการปรับให้เหมาะสมสำหรับพื้นที่โค้ด
วิธีแก้ไข: ใช้วงเล็บและวงเล็บปีกกาที่สมดุลเสมอในนิพจน์ภายใน f-strings
โค้ดตัวอย่าง:
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-strings ไม่รองรับการแปลง !a¶
สาเหตุ: MicroPython ไม่รองรับ ascii()
วิธีแก้ไข: ไม่มี
โค้ดตัวอย่าง:
f"{'unicode text'!a}"
CPython output: |
MicroPython output: |
Traceback (most recent call last):
File "<stdin>", line 8
SyntaxError: invalid syntax
|
import¶
แอตทริบิวต์ __path__ ของ package มีประเภทที่แตกต่างกัน (string เดียวแทนที่จะเป็น list ของ strings) ใน MicroPython¶
สาเหตุ: MicroPython ไม่รองรับ namespace packages ที่แบ่งออกข้ามระบบไฟล์ นอกจากนี้ระบบ import ของ MicroPython ได้รับการปรับให้เหมาะสมอย่างมากสำหรับการใช้หน่วยความจำน้อยที่สุด
วิธีแก้ไข: รายละเอียดการจัดการ import นั้นขึ้นอยู่กับ implementation โดยเนื้อแท้ อย่าพึ่งพารายละเอียดดังกล่าวในแอปพลิเคชันที่พกพาได้
โค้ดตัวอย่าง:
import modules
print(modules.__path__)
CPython output: |
MicroPython output: |
['/home/runner/work/openmv-doc/openmv-doc/micropython/tests/cpydiff/modules']
|
../tests/cpydiff/modules
|
MicroPython ไม่รองรับ namespace packages ที่แบ่งออกข้ามระบบไฟล์¶
สาเหตุ: ระบบ import ของ MicroPython ได้รับการปรับให้เหมาะสมอย่างมากสำหรับความเรียบง่าย การใช้หน่วยความจำน้อยที่สุด และการค้นหาระบบไฟล์น้อยที่สุด
วิธีแก้ไข: อย่าติดตั้งโมดูลที่อยู่ใน namespace package เดียวกันในไดเรกทอรีต่างกัน สำหรับ MicroPython แนะนำให้มี module search paths ไม่เกิน 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'
|