I would like to know what is the status of Subclassing native classes in Micropython.
Specifically, I have a C library which I expose in Micropython, and would like to subclass its objects in Micropython.
The official docs only mention that "Subclassing native classes is not fully supported in MicroPython" (https://micropython.org/resources/docs/ ... types.html).
Does anyone know what is actually supported and what is not when subclassing a native type or classes from a user added module?
Subclassing native classes
-
- Posts: 11
- Joined: Mon May 28, 2018 11:48 pm
Re: Subclassing native classes
As per the Exception.__init__ method does not exist. item I think the limitation is that you should use super().__init__() instead of BaseNativeClass.__init__() in constructors of your subclasses derived from native classes. And I guess you should check native_base_init_wrapper() function from py/objtype.c for details (or just search for "native_base" in this file and check the code). But I might be wrong...
In any case it would be better if you could include an example of your subclasses derived from native uPy classes as it's much easier to deal with some specific cases rather than describing all possible scenarios.
In any case it would be better if you could include an example of your subclasses derived from native uPy classes as it's much easier to deal with some specific cases rather than describing all possible scenarios.
Re: Subclassing native classes
Many answers can be found at https://en.wikipedia.org/wiki/Compositi ... nheritance
Awesome MicroPython list
Pycopy - A better MicroPython https://github.com/pfalcon/micropython
MicroPython standard library for all ports and forks - https://github.com/pfalcon/micropython-lib
More up to date docs - http://pycopy.readthedocs.io/
Pycopy - A better MicroPython https://github.com/pfalcon/micropython
MicroPython standard library for all ports and forks - https://github.com/pfalcon/micropython-lib
More up to date docs - http://pycopy.readthedocs.io/
Re: Subclassing native classes
The reason to use super is so that child classes that may be using cooperative multiple inheritance will call the correct next parent class function in the Method Resolution Order (MRO).
In Python 3, we can call it like this:
In Python 2, you were required to call super like this with the defining class's name and self, but you'll avoid this from now on because it's redundant, slower (due to the name lookups), and more verbose (so update your Python if you haven't already!):
Without super, you are limited in your ability to use multiple inheritance because you hard-wire the next parent's call:
In Python 3, we can call it like this:
Code: Select all
class ChildB(Base):
def __init__(self):
super().__init__()
Code: Select all
super(ChildB, self).__init__()
Code: Select all
Base.__init__(self) # Avoid this.