mirror of
https://github.com/micropython/micropython.git
synced 2025-09-07 10:20:52 +02:00
This adds a CPython diff that explains why calling `super().__init__()` is required in MicroPython when subclassing a native type (because `__new__` and `__init__` are not separate functions). Signed-off-by: David Lechner <david@pybricks.com>
32 lines
729 B
Python
32 lines
729 B
Python
"""
|
|
categories: Core,Classes
|
|
description: When inheriting native types, calling a method in ``__init__(self, ...)`` before ``super().__init__()`` raises an ``AttributeError`` (or segfaults if ``MICROPY_BUILTIN_METHOD_CHECK_SELF_ARG`` is not enabled).
|
|
cause: MicroPython does not have separate ``__new__`` and ``__init__`` methods in native types.
|
|
workaround: Call ``super().__init__()`` first.
|
|
"""
|
|
|
|
|
|
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")
|