Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Extending parent/children classes in python

Is it possible in python for a nested class to extend its parent?
Like this:

class Parent:
    class Child(Parent):
        pass

child = Parent.Child()

Is it possible to do this in the opposite direction?
Like this:

class Parent(Child):
    class Child:
        pass

parent = Parent()

From what I know this is not possible, even with from __future__ import annotations.
The best known way around this is just not to make nested classes.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

Important:
The purpose of this question is to make it clear if this is even possible in the python language.
There is no "final goal", objectives to be accomplished with this approach or justification for it.
Don’t spam in the comments/answers about "how bad this code is".

>Solution :

No and Yes.

No, because when you inherit from a class, that class must be defined before you can inherit from it. Neither of your code examples will work due to this.

Yes, because Python is a dynamic language and you can change (monkey-patch) the base classes even after defining them:

class Temp:
    pass

# example 1
class Parent:
    class Child(Temp):
        pass

Parent.Child.__bases__ = (Parent,)

# example 2
class Parent(Temp):
    class Child:
        pass

Parent.__bases__ = (Parent.Child,)

Why use the Temp class?

Classes automatically inherit from object. Due to a bug (https://bugs.python.org/issue672115), we cannot change __bases__ if a class inherits from object. Hence, we inherit from a temporary (Temp) class to avoid that issue.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading