mirror of
https://github.com/micropython/micropython.git
synced 2025-07-21 21:11:12 +02:00
When subclassing a native type, calling native members in `__init__` before `super().__init__()` has been called could cause a crash. In this situation, `self` in `mp_convert_member_lookup` is the `native_base_init_wrapper_obj`. The check added in this commit ensures that an `AttributeError` is raised before this happens, which is consistent with other failed lookups. Also fix a typo in a related comment. Signed-off-by: Laurens Valk <laurens@pybricks.com>
38 lines
859 B
Python
38 lines
859 B
Python
# test subclassing custom native class
|
|
|
|
try:
|
|
from cexample import AdvancedTimer
|
|
except ImportError:
|
|
print("SKIP")
|
|
raise SystemExit
|
|
|
|
|
|
class SubTimer(AdvancedTimer):
|
|
def __init__(self):
|
|
# At this point, self does not yet represent a AdvancedTimer instance.
|
|
print(self)
|
|
|
|
# So lookups via type.attr handler will fail.
|
|
try:
|
|
self.seconds
|
|
except AttributeError:
|
|
print("AttributeError")
|
|
|
|
# Also applies to builtin methods.
|
|
try:
|
|
self.time()
|
|
except AttributeError:
|
|
print("AttributeError")
|
|
|
|
# Initialize base class.
|
|
super().__init__(self)
|
|
|
|
# Now you can access methods and attributes normally.
|
|
self.time()
|
|
print(self.seconds)
|
|
self.seconds = 123
|
|
print(self.seconds)
|
|
|
|
|
|
watch = SubTimer()
|