Page 1 of 1

Subclassing native classes

Posted: Fri Jan 04, 2019 8:58 pm
by agonnen
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?

Re: Subclassing native classes

Posted: Mon Jan 14, 2019 11:21 am
by Maksym Galemin
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.

Re: Subclassing native classes

Posted: Mon Jan 14, 2019 8:01 pm
by pfalcon

Re: Subclassing native classes

Posted: Tue Apr 05, 2022 7:14 am
by paulwings
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:

Code: Select all

class ChildB(Base):
    def __init__(self):
        super().__init__()
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!):

Code: Select all

        super(ChildB, self).__init__()
Without super, you are limited in your ability to use multiple inheritance because you hard-wire the next parent's call:

Code: Select all

        Base.__init__(self) # Avoid this.